Node.js provides synchronous and asynchronous methods for opening files. Once a file is opened, you can read data from it or write data to it, depending on the flags used to open the file. To open files in a Node.js app, use one of the following statements for asynchronous or synchronous:
fs.open(path, flags, [mode], callback)
fs.openSync(path, flags, [mode])
The path
parameter specifies a standard path string for your file system. The flags
parameter specifies what mode to open the file in—read, write, append, etc., as described in Table 6.1. The optional mode
parameter sets the file access mode and defaults to 0666
, which is readable and writable.
Once a file has been opened, you need to close it to force flushing changes to disk and release the operating system lock. You close a file by using one of the following methods and passing the file descriptor to it. In the case of the asynchronous close()
call, you also need to specify a callback function:
fs.close(fd, callback)
fs.closeSync(fd)
The following is an example of opening and closing a file in asynchronous mode. Notice that a callback function is specified and receives an err
and an fd
parameter. The fd
parameter is the file descriptor that you can use to read or write to the file:
fs.open("myFile", 'w', function(err, fd){
if (!err){
fs.close(fd);
}
});
The following is an example of opening and closing a file in synchronous mode. Notice that there is no callback function and that the file descriptor used to read and write to the file is returned directly from fs.openSync()
:
var fd = fs.openSync("myFile", 'w'),
fs.closeSync(fd);