Node Js File Module

Node Js File module helps to interact with files on the system we are operating.
We need to import the “fs” module to use this feature of interacting with files. We can operate functions like reading files, write files, update files, rename files and delete files.
Fs module offers both ways to reading file, ie, synchronously and asynchronously.
fs.readFile() : reading file asynchronously
fs.readFileSync() : reading file synchronously
Let’s see some usage:
fs.readFile(fileName [,options], callback)
filename: file name with path
options: Optional params for setting encoding type and flag for r/rw.
callback: A function with two parameters err and fd. This will get called when readFile operation completes.
Commonly used flags
| r | Read a file. An exception occurs if file doesn’t exist. |
| r+ | Read and Write a file. An exception occurs if file doesn’t exist. |
| w+ | Read and Write a file. File is created if file doesn’t exist. |
| A | Append data to file. File is created, if file doesn’t exist. |
| W | Write on file. File is created, if file doesn’t exist. |
Let’s start with some examples.
Read data from a file
We have a text file: c:/test/datafile.txt and having content as “Hello world”
Let’s try to read this file. Create a javascript file and add below code
const fs = require('fs');
fs.readFile('c:/test/datafile.txt', 'UTF-8' function(err, data) {
if (err) return callback(err);
console.log(data);
});
Running this :
c:\test>node example6.js
Hello world !
Common Issues:
Missing encoding
Let’s remove the encoding
fs.readFile(‘c:/test/datafile.txt’, function(err, data) {…
and now run the file.
c:\test>node example6.js
<Buffer 48 65 6c 6c 6f 20 77 6f 72 6c 64 20 21>
File doesn’t exist
c:\test>node example6.js
{ [Error: ENOENT: no such file or directory, open ‘c:\test\datafile11.txt’]
errno: -4058,
code: ‘ENOENT’,
syscall: ‘open’,
path: ‘c:\\test\\datafile11.txt’ }
Read HTML file and print in the browser
Create a HTML file , c:/test/datafile.html and create a javascript file with below code which will read the html file and print it on browser.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('c:/test/datafile.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8081);
On running:
c:\test>node example6.js
Hello world !
Welcome to Learn Jobisite
Read file using streams
If the data is large, then it is recommended to use the stream for reading and writing into files.
Its concepts:
- source – the object where your data comes from
- pipeline – where your data passes through (you can filter, or modify it here),
- sink – where your data ends up.
Let’s see a simple javascript code using streams to read the file
const fs = require('fs')
const readableStream = fs.createReadStream('c:/test/datafile.txt')
readableStream.pipe(process.stdout);
On Running:
c:\test>node example6.js
Hello world !
Copy files
We can use stream classes to copy content from one file to another.
Lets create a sample javascript with below code.
const fs = require('fs')
const readableStream = fs.createReadStream('c:/test/datafile.txt')
var writableStream = fs.createWriteStream('c:/test/datafile-copy.txt')
readableStream.pipe(writableStream)
console.log("copied.")
On running:
c:\test>node example6.js
copied.
A new file is created “datafile-copy.txt’” with same content as datafile.txt
Write some data on a file.
Create a javascript file and add below code in that.
const fs = require('fs');
let data = 'Hello World\n' +
'Welcome to Learn Jobisite\n' +
'Writing done.';
fs.writeFile('c:/test/datafile.txt', data, (err) => {
if (err) throw err;
console.log('Data updated Successfully.');
});
Let’s understand the statements:
- We need to import ‘fs’ package which is required for interacting with file systems.
const fs = require(‘fs’);
- Create a sample data string to be added into the text file.
let data = ‘Hello World\n’ +
‘Welcome to Learn Jobisite\n’ +
‘Writing done.’;
- Write to a file, and if there are errors, throw an error.
fs.writeFile(‘c:/test/datafile.txt’, data, (err) => {
if (err) throw err;
console.log(‘Data updated Successfully.’);
});
Let’s run this
c:\test>node example6.js
Data updated Successfully.
And a file is created with the above text.
Common scenarios:
Let’s rerun the node file again
c:\test>node example6.js
Data updated Successfully.
The data in the file is again rewritten by same data. But not appended.
File cannot be created or path is not reachable
If the file path used is not correct.
fs.writeFile(‘f:/test/datafile.txt’, data, (err) => {….
And when we run the node application :
c:\test\example6.js:8
if (err) throw err;
^
Error: ENOENT: no such file or directory, open ‘f:\test\datafile.txt’
Another option to write on a file.
Use synchronous write options.
const fs = require('fs');
try {
const file = fs.writeFileSync('c:/test/datafile.txt', "Hello world");
} catch (err) {
console.error(err)
}
Checking file stat using fs.stat() /fs.statSync()
const fs = require('fs');
const status = fs.statSync('c:/test/datafile.txt');
console.log("Is File "+status.isFile());
console.log("Is Directory "+status.isDirectory());
console.log("Size "+status.size);
Now if we run this node command.
c:\test>node example6.js
Is File true
Is Directory false
Size 11
Append data to a file.
This is also a very commonly used function in node files module.
appendFile will append the content to the existing file. It doesn’t overwrite existing content but adds to the content. If a file doesn’t exist, then it creates a new one.
Let’s use below code in our javascript file and use a file which already has some content
var fs = require('fs');
fs.appendFile('c:/test/datafile.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
On running.
c:\test>node example6.js
Saved!
And the new content is added to the file.
Delete Files
Use fs.unlink(path, callback) to delete files.
Let’s use below code in our javascript file
var fs = require('fs');
fs.unlink('c:/test/datafile.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
On running
c:\test>node example6.js
File deleted!
And the file is removed from the system.
For synchronous operations, we have fs.unlinkSync().
Common Issues:
File doesn’t exist
if (err) throw err;
^
Error: ENOENT: no such file or directory, unlink ‘c:\test\datafile.txt’
Frequently Asked Questions
What are streams in Node.js?
These stream objects are used for reading and writing data as a continuous process.
Below are the available streams:
Readable -Reading operation.
Writable- Writing operation.
Duplex – Read and Write operations.
Transform- Computations on Inputs.
What is the difference between readFile and createReadStream?
Both are used for reading files.
The readFile returns data if the complete file is loaded into the buffer and can be read. It can be slow and can consume more memory if the file size is more.
The createReadStream process is partially buffered, and read files in chunks of data whose size can be defined. Unlike readFile, createReadStream is effective when it comes to reading and processing large files.
What are the timing features of Node.js?
The Timers module in Node.js contains functions to be executed after a certain time span.
setTimeout- schedule code execution after a certain time.
setInterval – execute a block of code multiple times
setImmediate -execute code at the end of the current event loop cycle
process.nextTick – execute in the next iteration of the Event Loop