Node File System
Manipulating Files
Modifying the files are a very common programming task. Node.js core API provides methods to make modifying a files as a trivial. There are a variety of file system methods, all contained in the fs module.
To use this module:
1 |
|
A few available functions
fs
simply provides a wrapper for the standard file operations, like:
- fs.readFileSync() to read files synchronously
- fs.readFile() to read files asynchronously
- fs.watch() for watching changes in files
- fs.exists() for checking that file exist
- fs.open() for opening the file
- fs.stat() for getting file attributes
- fs.read() for reading chuck of data from the file
- fs.writeFile() for writing to file
- fs.close() for closing the file
Read file
Create input.txt
file and store Sample text line in the file.
string inside it.
1 2 |
|
You can read the file with readFile
function. (error, data)
defines a callback function which will be called after a file reading has been finished.
1 2 3 4 5 6 |
|
Above programming will print the following lines to the console. Note how Line 6 will be called before the callback function will be called and line 2 or 3 has been executed.
1 2 |
|
Write file
The easiest way to write to files in Node.js is to use the writeFile()
.
1 2 3 4 5 6 7 8 9 |
|
By default, this API will replace the contents of the file if it does already exist. You can modify the default by specifying a flag.
1 |
|
The flags you'll likely use are
Flag | Description |
---|---|
r+ | This flag opens the file for reading and writing |
w+ | This flag opens the file for reading and writing and it also positions the stream at the beginning of the file |
w+ | This flag opens the file for reading and writing and it also positions the stream at the beginning of the file |
a+ | This flag opens the file for reading and writing and it also positions the stream at the end of the file |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Read more
Goals of this topic
Understand
- Node File System