How to read and write files in Node.js?

To manage files in Node, we use the fs module (a core module). We read and write files using the fs.readFile() and fs.writeFile() methods, respectively.

Steps to read and write files are shown below:

// Include http module,
var http = require(“http”),
fs = require(“fs”);

// Create the http server.

http.createServer(function (request, response) {
// Attach listener on end event.
request.on(‘end’, function () {
// Check if user requests /
if (request.url == ‘/’) {
// Read the file.
fs.readFile(‘test.txt’, ‘utf-8′, function (error, data) {
// Write headers.
response.writeHead(200, {
‘Content-Type': ‘text/plain’
});
// Increment the number obtained from file.
data = parseInt(data) + 1;
// Write incremented number to file.
fs.writeFile(‘test.txt’, data);
// End response with some nice message.
response.end(‘This page was refreshed ‘ + data + ‘ times!’);
});
} else {
// Indicate that requested file was not found.
response.writeHead(404);
// And end request without sending any data.
response.end();
}
});
// Listen on the 8080 port.
}).listen(8080);

This code demonstrates the fs.readFile() and fs.writeFile() methods. Every time the server receives a request, the script reads a number from the file, increments the number, and writes the new number to the file. The fs.readFile()method accepts three arguments: the name of file to read, the expected encoding, and the callback function.

Save this as files.js. Before you run this script, create a file named test.txt in the same directory as files.js.

Run application as $node file.js


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>