What are file module operations in Node.js?

The file module in Node.js makes it possible for someone to operate with their local file system while working on an IDE. It has various commands that make this possible.

  • The Create command helps us create a new file from IDE work space, so we don’t need to leave the environment.

  • The Read command helps us read a file on the local file system of the computer by using the file name and the read command.

  • The Update command helps in updating an already existing file on the computer.

  • The Rename command helps to rename a file already stored in the computer.

  • The Delete command is used to delete files present on the computer.

To use the file module, we must have Node pre-installed in computer, and then we need to require the file module fs.

 var fs = require('fs')

This makes the module available for use. To create a file after requiring the file module, we now use the possible commands: fs.appendFile() , fs.open() or fs.writeFile().

We will use fs.writeFile() below.

var fs = require('fs');
fs.writeFile('filecreation.txt','my first file is created',function(err){
    if(err) throw err;
    console.log('new file created');
});

To read an HTML file kept in the same folder with the Node file, we use the fs.readfile() method below.

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('myFile.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

To update a file through the file module, we can use either the fs.writeFile() command or the fs.appendFile() command. This would copy right into the .txt file the written words, and this gets the file updated.

var fs = require('fs');

fs.appendFile('filecreation.txt', ' This is a new text to the file.', function (err) {
  if (err) throw err;
  console.log('latest file update');
});

We can also delete a file through the file system by using the fs.unlink() method. This command deletes the filecreation.txt from the below line of code.

var fs = require('fs');

fs.unlink('filecreation.txt', function (err) {
  if (err) throw err;
  console.log('This file was deleted!');
});

We can also rename a file through the Node file module system by using the fs.rename() method. This method renames the file in the code below.

var fs = require('fs');

fs.rename('filecreation.txt', 'newfilecreation.txt', function (err) {
  if (err) throw err;
  console.log('old file name changed');
});

Conclusion

The Node file module is essential in communicating with the local file system of the user’s computer while working on the Node environment.

Free Resources