Node.js fs.open() Method
Introduction: To create file, to write to a file or to read a file fs.open() method is used. fs.readFile() is only for reading the file and similarly fs.writeFile() is only for writing to a file, whereas fs.open() method does several operations on a file. First we need to load the fs class which is module to access physical file system. For it require method is used. For example: var fs = require(‘fs’);
fs.open( filename, flags, mode, callback )
Parameter: This method accept four parameters as mentioned above and described below:
- filename: It holds the name of the file to read or the entire path if stored at other location.
- flag: The operation in which file has to be opened.
- mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite.
- callback: It is a callback function that is called after reading a file. It takes two parameters:
- err: If any error occurs.
- data: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file.
All the types of flags are described below:
Flag Description r To open file to read and throws exception if file doesn’t exists. r+ Open file to read and write. Throws exception if file doesn’t exists. rs+ Open file in synchronous mode to read and write. w Open file for writing. File is created if it doesn’t exists. wx It is same as ‘w’ but fails if path exists. w+ Open file to read and write. File is created if it doesn’t exists. wx+ It is same as ‘w+’ but fails if path exists. a Open file to append. File is created if it doesn’t exists. ax It is same as ‘a’ but fails if path exists. a+ Open file for reading and appending. File is created if it doesn’t exists. ax+ It is same as ‘a+’ but fails if path exists.
Below examples illustrate the fs.open() method in Node.js:
The file is opened and the flag is set to read mode. After opening of file function is called to read the contents of file and store in memory. As there are no errors ‘saved’ is printed.
Open file! 10 File Opened!
Explanation: The file ‘demo.txt’ is opened in read and write mode, then the function is called. Output shows a number in file when we print value of ‘f’.