Node.js for beginners: the basics of working with files

Original author: Akhil Goyal
  • Transfer
  • Tutorial
Today we’ll talk about how to work with the file system using Node.js, consider the basic operations performed with files. Such operations include the following:

  • File creation
  • Read file
  • Writing data to a file
  • File deletion
  • Rename file

The need to perform such operations arises in a variety of situations.



Fs module


Node.js has a standard module fs(short for File System) that gives the developer tools for working with the file system. You can import it into the project as follows:

var fs = require(‘fs’);

The methods of this module are presented in synchronous and asynchronous forms. The callback functions passed to asynchronous methods accept an error object as the first parameter, and data returned when the operation was successful as the second parameter. Consider an example:

function fileHandler(){
    fs.readFile('textFile.txt', 'utf8', (err, data) => {
        if(err) throw err;
        console.log(data);
    });
}

The method .readFile()we are going to talk about is for reading files. In this example, the callback function has two parameters - errand data. Errors that may occur when trying to read a file fall into the first parameter, data obtained after a successful operation are in the second parameter. Note that .readFile()this is an asynchronous module method fs. Its synchronous version is called .readFileSync(). A similar approach is used to name other module methods.

Create a new file


Let's start with an example:

function fileHandler(){
    fs.open('testFile.txt', 'w', (err) => {
        if(err) throw err;
        console.log('File created');
    });
}

Here, the method is fs.open()used to create a new file. It takes a file name as the first argument. His second argument is a flag that tells the system exactly what we want to do with the file. In this case, this is a flag w(short for writing), which indicates that we want to open the file for writing. The method .open()can accept various flags. Here is some of them:

  1. r: open file for reading
  2. r+: open file for reading and writing
  3. rs: open file for reading in synchronous mode
  4. w: open file for writing
  5. a: open file to write data to end of file
  6. a+: open the file for reading and writing data to the end of the file

Now, before moving on to the next example, we’ll edit the file we just created testFile.txtusing some kind of text editor. Add the following text to it:

This is a test file.
We're learning about Node.js File System.
The End.

Writing data to a file


Let's talk about how to add something to a file:

function fileHandler(){
    fs.appendFile('testFile.txt', ' This line is beyond the end.', (err) => {
        if(err) throw err;
        console.log('Data has been added!');
    });
}

Here we use a method .appendFile()to add data to the end of an existing file. As the first argument, this method accepts the file name, as the second - the data that needs to be added to the end of the file. The third argument is, as usual, a callback function.

After the code shown above executes successfully, the contents of the file will look like this:

This is a test file.
We're learning about Node.js File System.
The End. This line is beyond the end.

There is another way to write data to a file. It implies the use of a method .writeFile(). This method is very similar to .appendFile(), but it has one important difference. The fact is that with the help of the method .appendFile()we add new data to the file after the data that is already in it. And when using the method, the .writeFile()contents of the file are replaced with a new one. Let's try this method:

function fileHandler(){
    fs.writeFile('testFile.txt', "I'm the replacement you've been looking for.", (err) => {
        if(err) throw err;
        console.log('Data has been replaced!');
    });
}

After successful operation, the file will contain the following text:

I'm the replacement you've been looking for.

As you can see, the contents of the file are completely replaced by a new one.

Read file


The module fsprovides a method for reading files .readFile(), an example of the use of which we have already seen. It takes the file name as the first parameter, and the encoding as the second. The third parameter is the callback function. Let's try to print the contents of the file to the console testFile.txtusing this method:

function fileHandler(){
    fs.readFile('testFile.txt', 'utf8', (err, data) => {
        if(err) throw err;
        console.log('--------- [File Data] ---------');
        console.log(data);
        console.log('--------- [File Data] ---------');
    });
}

That's what we get.


File data displayed in the console

Now let's talk about renaming files.

Rename file


To rename files, use the method .rename():

function fileHandler(){
    fs.rename('testFile.txt', 'newTestFile.txt', (err) => {
        if(err) throw err;
        console.log('File renamed successfully!');
    });
}

The first argument of the method is the name of an existing file, the second is the new name of this file. After a successful call to this method, the file testFile.txtturns into newTestFile.txt.

File deletion


To delete files, use the method .unlink():

function fileHandler(){
    fs.unlink('newTestFile.txt', (err) => {
        if(err) throw err;
        console.log('File deleted successfully!');
    });
}

A successful call to this method deletes the file newTestFile.txt.

Summary


In this article, we examined the basics of working with the file system in Node.js. If you want to master this topic more deeply, take a look at this material from the Node.js publication cycle, read the module documentationfs and try to try out everything you learn in practice.

Dear readers! Do you use the standard fs module or something else to work with files in Node.js?


Also popular now: