-
Notifications
You must be signed in to change notification settings - Fork 19
WorkingWithFileSystem
In this chapter, we're going to learn how to read local files and write text data to a local file. Note that only UTF-8 encoded text files are supported.
To handle local files, use FileSystem and FileUtils modules.
var FileSystem = app.getModule("filesystem/FileSystem"),
FileUtils = app.getModule("file/FileUtils");
To read a text file, you need to create a File object with a full pathname of an existing file. And then, you can read the text using FileUtils.readAsText
function. It returns JQuery's Promise object, so you need to pass callback functions to get the text data in the file or error message. Following is an example reading a local text file.
var file = FileSystem.getFileForPath("/Users/niklaus/my-file.txt");
FileUtils.readAsText(file)
.done(function (data) {
console.log(data);
})
.fail(function (err) {
console.error(err);
});
Writing to a file is similar to the reading. First, you need to create a File object with full pathname and prepare string object to write. And then, you can write the string into a local file by calling FileUtils.writeText
function. The first parameter is the file object and the second parameter is the string object. The third parameter indicates whether or not CONTENTS_MODIFIED
errors should be ignored (In most cases, just pass true
).
var file = FileSystem.getFileForPath("/Users/niklaus/my-new-file.txt");
var text = "First line\nSecond line\nThird line...";
FileUtils.writeText(file, text, true)
.done(function () {
console.log("File saved.");
})
.fail(function (err) {
console.error(err);
});
To create a directory, create a Directory object with a full pathname and then call create
method of the directory object.
var directory = FileSystem.getDirectoryForPath("/Users/niklaus/my-dir");
directory.create();
If you need to get all contents of a particular directory, you can get an array object by calling getContents
method. The contents
passed to the callback function is a array of FileSystemEntry object which is a super-class of File and Directory classes. For more fields and methods, please refer to API Docs.
var directory = FileSystem.getDirectoryForPath("/Users/niklaus");
directory.getContents(function (err, contents) {
if (!err) {
for (var i = 0; i < contents.length; i++) {
if (contents[i].isDirectory) {
console.log("DIR: " + contents[i].name);
} else {
console.log("FILE: " + contents[i].name);
}
}
} else {
console.error(err);
}
});