Working with the file system
fs module
QX.js includes the fs module, which provides an API for interacting with the file system on your computer. fs modules APIs are inspired from the Node.js ‘fs’ module API.
Common uses for the file system module:
-
Read files
-
Create files
-
Update files
-
Delete files
Asynchronous and Synchronous
Every method in the fs module has synchronous as well as asynchronous forms, except read and write files. Methods take the last parameter as the completion function callback and the first parameter of the callback function as error. It is better to use an asynchronous method instead of the asynchronous method, as the former never blocks the script or application during its execution, whereas the second one does.
File path
Most fs operations accept file paths that can only be specified in the form of a string. String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will work only on Windows and they will be resolved relative to the current QuarkXPress location.
Best Practices
-
Use
app.dirproperties to access or create a file path relative to QuarkXPress location. -
Use the
app.getUserScriptsFolder()method to access or create a file relative to the user path JavaScript. -
Use a forward slash (/) as a file separator to create a cross-platform file path.
The following sections in this chapter provide a set of good examples on major File I/O methods.
Reading Files
Use the fs.readFileSync() method to read the physical file synchronously.
Method Signature: fs.readFileSync(fileName)
Parameters:
-
filename: Full path and name of the file as a string.
Example
let data = fs.readFileSync('C:/DATA/file.txt');
console.log(data);
To read file from user documents:
let userDocuments = app.getUserScriptsFolder()+'/../../../';
let data = fs.readFileSync(userDocuments+'file.txt');
Samples Using this method
Writing Files
Use the fs.writeFileSync() method to write data to a file. If a file already exists then the existing content
will be overwritten, otherwise a new file is created.
Method Signature: fs.writeFile(filename, data)
Parameters:
-
filename: Full path and name of the file as a string. -
Data: The content to be written in the file as a string.
Example
let filePath = app.getUserScriptsFolder()+'/../../../file.txt';
fs.writeFileSync(filePath, "file content");
This will create a new file in the user documents folder if the file does not exist.
Delete Files
Use the fs.unlink() method to delete an existing file.
Method Signature: fs.unlink(path, callback);
Parameters:
-
filename: Full path and name of the file as a string. -
callback: A function gets called when file delete operation completes. No arguments other than a possible exception are given to the completion callback.
Example
fs.unlink('test.txt', function () {
if (err) throw err;
console.log('delete operation complete.');
});
Use the fs.unlinkSync('file path') method to delete an existing file synchronously.
let filePath = app.getUserScriptsFolder()+'/../../../file1.txt';
fs.unlinkSync(filePath);
Read Directory
Use the fs.readdir() method to read the contents of a directory.
Method Signature: fs.readdir(path, callback);
Parameters:
-
filename: Full path and name of the file as a string. -
callback: A function gets called when the reading directory operation completes. The callback takes two arguments (err, files) where files is an array of the names of the files.
Example
Use the following example to read the directory contents:
let userDocumentsPath = app.getUserScriptsFolder()+'/../../../../Documents'
fs.read(userDocumentsPath , function (files) {
console.log('array of files.', files);
});
Use the fs.readdirSync(path) method to reads the contents of a directory synchronously.
let userDocuments = fs.readdirSync(userDocumentsPath ) ;
console.log(userDocuments);
File information
Use the fs.stat() method to retrieve information about a file.
Method Signature: fs.stat(path, callback);
Parameters:
-
path: Full path and name of the file as a string. -
callback: A function gets called when an operation completes. The callback takes two arguments, (err, stats) where stats is an fs.Stats object.
Two useful methods available in the fs.Stats class which can be used to check file type:
-
stats.isDirectory(): Returns true if the file type is a directory. -
stats.isFile(): Returns true if the file type is a simple file.
Example
The following example retrieves the file information:
fs.stat('test.txt', function (fileStat) {
console.log(fileStat);
})
Use the fs.statSync(path) method to retrieve the information about a file synchronously.
let filePath = app.getUserScriptsFolder()+'/../../../file1.txt';
let fileStat = fs.stat(filePath);
console.log(fileStat.isFile());
File Exist
Use the fs.exist() method to test whether or not the given path exists by checking with the file system.
Method Signature: fs.stat(path, callback);
Parameters:
-
path: Full path and name of the file as a string. -
callback: A function gets called when the operation completes. The callback has only one boolean parameter.
Use the fs.existSync(path) method to test file existence synchronously.
Create Directory
Use the fs.mkdir() method to create a directory.
Method Signature: fs.mkdir(path,[mode], callback)
Parameters:
-
path: This is the directory name including path. -
mode: This is the directory permission to be set. Defaults to 0777. Currently not supported. -
callback: This is the callback function. No arguments other than a possible exception are given to the completion callback.
Example
The following example creates the directory in the documents folder of the user.
let folderPath = app.getUserScriptsFolder()+'/../../../myFolder';
fs.mkdir(folderPath , function () {
console.log("Directory created successfully!");
} );
Use the fs.mkdirSync(path) method to create a directory synchronously.
let fileStat = fs.stat(folderPath);
console.log(fileStat.isFile());
Remove Directory
Use the fs.rmdir() method to remove a directory.
Method Signature: fs.rmdir (path, callback)
Parameters:
-
path: This is the directory name including path. -
callback: This is the callback function. No arguments other than a possible exception are given to the completion callback.
Example
The following example deletes the 'myFolder' directory in the documents folder of the user:
let folderPath = app.getUserScriptsFolder()+'/../../../myFolder';
fs.rmdir(folderPath , function () {
console.log("Directory deleted successfully!");
} );
Use the fs.rmdirSync(path) method to delete directory synchronously.
Copy Files
Use the fs.copyFile() to asynchronously copy files. By default, if the file already exists in the destination,
it will be overwritten.
Method Signature: fs.copyFile(src, dst, flags, callback)
Parameters:
-
src: Source path of the file to copy. -
dst: Destination path of the copy operation. -
flags: An optional integer that specifies the behavior of the copy operation. Default: 0 Currently not supported. -
callback: This is the callback function. No arguments other than a possible exception are given to the completion callback.
Example
The following example copies the ' file.txt' file from the documents folder to the "C" drive of the user system:
let src = app.getUserScriptsFolder()+'/../../../file.txt';
let dest = "C:\\file.txt";
fs.copyFile(src, dest, 0, () => {
console.log("file copied successfully")
})
Use the fs.copyFileSync(src, dst, flag) method to copy file synchronously.