This tutorial explains how to access the file system and read / write files using Node.js libraries. This tutorial explains about a module called fs for interacting with file system.
I have written various Node.js articles covering the topics Scheduling Tasks in Node.js using Cron Package, ExpressJS and Bootstrap development and Node.js and MongoDB CRUD Operations. Also learn about how to package and deploy the Node.js application.
Node.js provides a module called fs for interacting with file system. This includes not just reading/writing to file, but also includes more things like linking files, permissions related to files and directories, watching files, directories for changes and others. Node.js file operations has lot more, here I explain only read and write APIs.
- Book Reference : Web Development with Node and Express
In this post I will show you how to read from files and write to files both synchronously and asynchronously in Node.js using this fs module. File API defines each method with both synchronous and asynchronous version. You can either use the synchronous call or asynchronous call to read, write and remove files.
I assume that you have enough exposure to Node.js for setting up and import the packages. So, i would focus only on explaining the Node.js file operations in this tutorial.
Node.js File Operations
There are quite a few ways of reading the file. In this post I am going to show two ways:
- using the readFile API.
- using the ReadStream API
Reading File Asynchronously – readFile API
This example helps you to read a file asynchronously using the readFile() method.
//Filename: node-read-async.js var fs = require('fs'); var readSource = 'C:/input.txt'; /** Using the readFile API - Asynchronous */ fs.readFile(readSource, "utf8", function(err, data){ if ( err ){ throw err;} console.log("Reading file asynchronously"); console.log(data); });
Run the above code by executing: node node-read-async.js
The output we get:
G:\node\node-file-io>node node-read-async.js Reading file asynchronously As an asynchronous event driven framework, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection the callback is fired, but if there is no work to be done Node is sleeping.
Reading File Synchronously – readFileSync API
//Filename: node-read-sync.js var fs = require('fs'); var readSource = 'C:/input.txt'; /** Using the readFile API - Asynchronous */ console.log("Reading file synchronously"); var fileData = fs.readFileSync(readSource, "utf8"); console.log(fileData);
Executing the above we get:
G:\node\node-file-io>node node-read-sync.js Reading file synchronously As an asynchronous event driven framework, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection the callback is fired, but if there is no work to be done Node is sleeping.
Reading File – ReadStream API
var fs = require('fs'); var readSource = 'C:/input.txt'; /** Reading file using ReadStream API */ //Creating a stream out of the file var readStreamObject = fs.createReadStream(readSource, { flags: 'r', encoding:"utf8", fd: null, mode: 0666, autoClose: true }); //Setting up event handlers on the stream object //readable - this event is fired when data can be read from stream readStreamObject.on('readable', function(){ console.log("*** Reading from file using ReadStream"); }); //data - this event is fired when data is available to be read from stream readStreamObject.on('data', function(data){ console.log(data); }); //end - this event is fired when there is no more data available to be read from stream readStreamObject.on('end', function(){ console.log("*** Completed Reading from file using ReadStream"); });
Executing the above code as shown below we get:
G:\node\node-file-io>node node-read-readstream.js As an asynchronous event driven framework, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection the callback is fired, but if there is no work to be done Node is sleeping. *** Reading from file using ReadStream *** Completed Reading from file using ReadStream
Above you might notice that the event handling is not in order, i.e one would expect the message “*** Reading from file using ReadStream” first, then the contents of the file and then finally “*** Completed Reading from file using ReadStream”. But due to the async nature of the API the order is not guaranteed.
Write To File Asynchronously – writeFile API
var fs = require('fs'); var writeSource = 'C:/Users/Mohamed/Documents/node-write-demo.txt'; fs.writeFile(writeSource, "Writing to a file from node.js", {"encoding":'utf8'}, function(err){ if ( err ) { throw err; } console.log("*** File written successfully"); //Now reading the same file to confirm data written fs.readFile(writeSource, "utf8", function(err, data){ if ( err ){ throw err;} console.log("*** Reading just written file"); console.log(data); }); });
Executing the above script we get:
G:\node\node-file-io>node node-write-async.js *** File written successfully *** Reading just written file Writing to a file from node.js
Write To File Synchronously – writeFileSync API
var fs = require('fs'); var writeSource = 'C:/Users/Mohamed/Documents/node-write-sync-demo.txt'; fs.writeFileSync(writeSource, "Writing to a file synchronously from node.js", {"encoding":'utf8'}); console.log("*** File written successfully"); //Now reading the same file to confirm data written fs.readFile(writeSource, "utf8", function(err, data){ if ( err ){ throw err;} console.log("*** Reading just written file"); console.log(data); });
Executing the above script we get:
G:\node\node-file-io>node node-write-sync.js *** File written successfully *** Reading just written file Writing to a file synchronously from node.js
Write To File – WriteStream API
var fs = require('fs'); var writeSource = 'C:/Users/Mohamed/Documents/node-write-stream-demo.txt'; //Create a stream with the required path var writeStreamObject = fs.createWriteStream(writeSource); //write to the stream using the API writeStreamObject.write("Writing to a file using WriteStream", "utf8"); //Now read the same file to verify that the contents have been successfully written fs.readFile(writeSource, "utf8", function(err, data){ if ( err ){ throw err;} console.log("*** Reading the recently written file"); console.log(data); });
Executing the above script we get:
G:\node\node-file-io>node node-write-writestream.js *** Reading the recently written file Writing to a file using WriteStream
Summary
This tutorial explained how to read and write file using the the fs package in Node.js. There are two types of methods defined for each operations (read, write and removed), synchronous and asynchronous. With this I have shown different ways in which we can read and write to files in Node.js. If you have any questions, please write it in the comments section.