- 
                Notifications
    You must be signed in to change notification settings 
- Fork 20
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 read a text file, use FileSystem and FileUtils modules.
var FileSystem = app.getModule("filesystem/FileSystem"),
    FileUtils  = app.getModule("file/FileUtils");First, 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 also 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);
    });var directory = FileSystem.getDirectoryForPath("/Users/niklaus/my-dir");
directory.create();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);
    }
});