WinJs getFileAsync without stating a folder first - javascript

I have a string to the path of a file, and i would like to get the file. So far i have only found this, which relies on the file being within a specified folder, or a child of this folder.
var rootFolder = Windows.Storage.ApplicationData.current.localFolder;
rootFolder.getFileAsync('MY_FILE_PATH_FROM_ROOT').then(function (file) {
});
By rootFolder points to a folder where the app is installed, something like C:\Program Files....
What if i have a filePath string of something like C:\MyFiles\Picture\Pic_123.png. How would i get this file?
Sorry i am new to WinJs.

Kind of simple once you see the API. Use
Windows.Storage.StorageFile.getFileFromPathAsync('YOUR_FILE_PATH')
.then(function (file) {
});

Related

How can I get an input folder and its files using Javacript for Automator?

I am writing an automator workflow to work with files and folders. I’m writing it in JavaScript as I’m more familiar with it.
I would like to receive a folder, and get the folder’s name as well as the files inside.
Here is roughly what I have tried:
Window receives current folders in Finder (I’m only interested in the first and only folder)
Get Folder Contents
JavaScript:
function run(input,parameters) {
var files = [];
for(let file of input) files.push(file.toString().replace(/.*\//,''));
// etc
}
This works, but I don’t have the folder name. Using this, I get the full path name of each file, which is why I run it through the replace() method.
If I omit step 2 above, I get the folder, but I don’t know how to access the contents of the folder.
I can fake the folder by getting the first file and stripping off the file name, but I wonder whether there is a more direct approach to getting both the folder and its contents.
I’ve got it working. In case anybody has a similar question:
// Window receives current folders in Finder
var app = Application.currentApplication()
app.includeStandardAdditions = true
function run(input, parameters) {
let directory = input.toString();
var directoryItems = app.listFolder(directory, { invisibles: false })
var files = [];
for(let file of directoryItems) files.push(file.toString().replace(/.*\//,'')) ;
// etc
}
I don’t include the Get Folder Contents step, but iterate through the folder using app.listFolder() instead. The replace() method is to trim off everything up to the last slash, giving the file’s base name.

how open transform xml file that is in my project folder in Javascript Object

I'm new to react native. I'm trying to transform an xml file into a Javascript object for parse it after. My problem is that I am not able to pass at readFile method, the path of my project folder.
I'm using react-native-fs module, in this mode:
var RNFS = require('react-native-fs'),
xml2js = require('react-native-xml2js');
parser = new xml2js.Parser()
RNFS.readFile(what path?, (err, data) ->
parser.parseString data, (err, result) ->
console.dir result
console.log 'Done.'
Someone can help me?
thanks.
P.s.
My project structure is:
Myapp
|--->App
| |--->Components
| |--->Xml
|--->Android
|--->``Ios
...
How can I reference xml folder in my code?
there are APIs in 'react-native-fs'/FS.common.js to get directory paths.for example:DocumentDirectoryPath, ExternalStorageDirectoryPath, ExternalDirectoryPath etc.
it depends on where the file is
read file in the bundle on Android. use
RNFS.readFileAssets("a/b/c.txt")
read file in the app own director on Android and iOS, use
RNFS.readFile(RNFS.DocumentDirectoryPath + "/a/b/c.txt")
read file in sdcard on Android, use
RNFS.readFile(RNFS.ExternalDirectoryPath + "/a/b/c.txt")

Editing a file within a zipped file using JSZip

Using JSZip, is there a way to edit a file within a zipped file?
I've tried looking for solutions and going through the API but I can't seem to find a solution.
Any help with this would be great! Thanks in advance!
You can edit a file inside your zip with .file method.
zip.file("existing_filename", "new file content");
This method is used for adding and updating file content.
Just make sure the file already exist.
You can read more about it in the documentation.
You can refer to the official documentation.
And here's a more complete Node.js example:
var fs = require("fs");
var JSZip = require("jszip");
async function zipDemo() {
// read the existing zip file
var zipData = fs.readFileSync("input.zip");
var zip = await JSZip.loadAsync(zipData);
// add a new JSON file to the zip
zip.file("sample.json", JSON.stringify({demo:123}));
// write out the updated zip
zip.generateNodeStream({type:'nodebuffer', streamFiles:true})
.pipe(fs.createWriteStream('output.zip'))
.on('finish', function () {
console.log("output`enter code here`.zip written.");
});
}
zipDemo();

How to create a folder in Firebase Storage?

So the new Firebase has support for storage using Google Cloud Platform.
You can upload a file to the images folder using:
var uploadTask = storageRef.child('images').put(file, metadata);
What if you want to create a subfolder images/user1234 dynamically using code?
The offical sample does not show how to do that, nor the official guide or reference docs.
Is the Firebase Console the only place where folders can be created manually?
The Firebase Storage API dynamically creates "folders" as intermediate products: if you create a file at images/user1234/file.txt, all intermediate "folders" like "images" and "user1234" will be created along the way. So your code becomes:
var uploadTask = storageRef.child('images/user1234/file.txt').put(file, metadata);
Note that you need to include the file name (foo.txt for example) in the child() call, since the reference should include the full path as well as the file name, otherwise your file will be called images.
The Firebase Console does allow you to create a folder, since it's the easiest way to add files to a specific folder there.
But there is no public API to create a folder. Instead folders are auto-created as you add files to them.
You most certainly can create directories... with a little bit of playing with the references I did the following.
test = (e,v) => {
let fileName = "filename"
let newDirectory = "someDir"
let storage = firebase.storage().ref(`images/${newDirectory}/${fileName}`)
let file = e.target.files[0]
if(file !== undefined && file.type === "image/png" ) {
storage.put(file)
.then( d => console.log('you did it'))
.catch( d => console.log("do something"))
}
}
String myFolder = "MyImages";
StorageReference riversRef = storageReference.child(myFolder).child("images/pic.jpg");
Firebase is lacking very important functionality, there's always the need to be doing some tricks to emulate behaviours that should be standard.
If you create a folder manually from the Firebase console it will
persist even when there are no more files in it.
If you create a folder dynamically and all files get deleted at some
point, the folder will disappear and be deleted as well.
I implemented a file manager using Firebase Storage so when a user wants to upload a file he can do it through this interface not from something external to the app as is the Firebase Console. You want to give the user the option to reorganize the files as he wants, but something as common as creating a new folder cannot be done without tricks, why? just because this is Firebase.
So in order to emulate this behaviour what I came up with was the following:
Create a reference with the new folder name.
Create a reference for a "ghost" file as child of the folder's reference and give it always the same fixed name, eg. '.ghostfile'
Upload the file to this newly created folder. Any method is valid, I just use uploadString.
Every time I list the files of a reference, exclude any file named as before. So this "ghost" file is not shown in the file manager.
So an example to create a foler:
async function createFolder (currentRef: StorageReference, folderName: string) {
const newDir = ref(currentRef, name)
const ghostFile = ref(newDir, '.ghostfile')
await uploadString(ghostFile, '')
}
And an example to list the files:
async function loadLists (ref: StorageReference) {
const { prefixes, items } = await listAll(ref)
return {
directories: prefixes,
files: items.filter(file => file.name !=== '.ghostfile')
}
}
Firebase console allows you to create a folder. I don't think there is another way to create a folder.

Creating zip file only contains pdf

In my script I am trying to create a folder, create a date-stamped-document in said folder, create a sub folder, and copy some documents into that sub folder.
All of this works great. When I try to zip the parent folder via either of the methods found here: Creating a zip file inside google drive with apps script - it creates a zip file with a sole PDF file that has the same name as the date-stamped-document. The zipped PDF is blank, and the subfolder isn't there.
Any insight about why this is happening would be great.
var folder = DocsList.createFolder(folderTitle);
var subFolder = folder.createFolder('Attachments');
subfolder.createFile(attachments[]); //In a loop that creates a file from every
//attachment from messages in thread
var doc = DocumentApp.create(docTitle); //Google Doc
var docLocation = DocsList.getFileById(doc.getId());
docLocation.addToFolder(folder);
docLocation.removeFromFolder(DocsList.getRootFolder());
//Everything works fine, I can view file and subfolder, and subfolder's documents
//This is where the problem is:
var zippedFolder = DocsList.getFolder(folder.getName());
zippedFolder.createFile(Utilities.zip(zippedFolder.getFiles(), 'newFiles.zip'));
//this results in a zipped folder containing one blank pdf that has the same title as doc
The DocsList service has been deprecated so Phil Bozak's previous solution no longer works. However, refer to another SO question for solution that works with DriveApp class.
This is a great question. It does not seem that the zip function has the ability to zip sub folders. The reason that your script doesn't work is because you only select the files from the folder.
A solution would be to zip each of the subfolders and store that in the one zipped file. You can use the function that I wrote for this.
function zipFolder(folder) {
var zipped_folders = [];
var folders = folder.getFolders();
for(var i in folders)
zipped_folders.push(zipFolder(folders[i]));
return Utilities.zip(folder.getFiles().concat(zipped_folders),folder.getName()+".zip");
}
This recursively zips all subfolders. Then you need to create the file with something like
DocsList.getFolder("path/to/folder/to/store/zip/file").createFile(zipFolder(folderToZip));
I will put in a feature request to allow subfolders to be zipped.

Categories

Resources