Computer scienceBackendNode.jsCore ConceptsInternal modulesFile system module

Write to file

7 minutes read

Writing files is one of the basic tasks that developers do in their everyday work. Like any other server-side language, Node.js lets us choose between overwriting an existing file or appending to it. In a few minutes, you will learn how to do these operations using fs.writeFile() and fs.appendFile() and their corresponding synchronous methods.

Let us add some fun and try to create some basic functionality of the Notes app using the above-mentioned functions.

Writing files

First of all, initialize a constant and require the fs module:

const fs = require('node:fs');

Andy is an active user of the Notes app. He is flying to Dubai next week, and he wants to write down the trip's details as a reminder. Our task is to take his note and write it to a new file. We will use one file per note. Before implementing the actual code, let's quickly go through the syntax of the writeFile() method:

fs.writeFile(file, data, [options], callback)

The first argument is a filepath of the file we want to write, the data is the content (in our case Andy's note). The options, as they indicate, are optional, they include encoding (utf-8, base64, etc), mode and flags. We'll talk more about flags later. Finally, the callback fires off when the data is written successfully. We'll omit the options for now, and here is what we basically have for writing Andy's first note:

const fs = require('node:fs');

const firstNote = 'Dates: 25/12 - 01/01, Heathrow airport 9:15 AM, need to book a room';

fs.writeFile('firstNote.txt', firstNote, (err) => {
    if (err) {
        console.log(err);
    }
    console.log('The first note is written, yay!');
})

Passing an invalid callback to the callback argument, throws ERR_INVALID_ARG_TYPE.

If you run your node command, you should see a new file firstNote.txt created in the same directory. As a default, Node will look for the file to write and if it doesn't exist, it will create it. By the way, you may work with any file extensions like .js, .json, .html, etc.

What if you change the firstNote variable and run the code again? Will the new text be added to the file, or will it be completely overwritten? You may try that on your computer, and you should see that the old data has been replaced by the new value. There is a workaround, we will talk about it in the next sections.

That was the asynchronous way of writing files, but we can achieve the same results using the synchronous fs.writeFileSync() method. The main difference in the syntax is that the sync method doesn't have a callback.

const fs = require('node:fs');

const firstNote = 'Dates: 25/12 - 01/01, Heathrow airport 9:15 AM, need to book a room';

fs.writeFileSync('firstNote.txt', firstNote);

In real-world applications, asynchronous methods are more common and preferable because they do not block the event loop.

Appending files

Andy revisits his Notes app and notices that he needs to add more info related to the trip. Here is how to accomplish this using the fs.appendFile() method:

const fs = require('node:fs');

const newInfo = ' and rent a car';

fs.appendFile('firstNote.txt', newInfo, (err) => {
    if (err) {
        console.log(err);
    }
    console.log('New info added, cool!');
})

If you check your firstNote.txt file, you will see that it now looks like this:

Result of appendFile method in the firstNote.txt file with the content – Dates: 25/12 - 01/01, Heathrow airport 9:15 AM, need to book a room

We were able to add new data, preserving the old text, cool!

As you can see, the syntax is pretty much the same as with the fs.writeFile() method. The synchronous one looks identical as well:

const fs = require('node:fs');

const newInfo = ' and rent a car';

fs.appendFileSync('firstNote.txt', newInfo);

Flags

The default behavior of the fs.writeFile() method is overwriting an existing file if the content changes. We can control that by specifying flags in the options argument. For example, you can use the "a" flag to say that you want to append the data but still retain the original content. Check out this code snippet:

const fs = require('node:fs');

const newInfo = ' and learn Node.js on the plane';

fs.writeFile('firstNote.txt', newInfo, {flag: 'a'}, (err) => {
    if (err) {
        console.log(err);
    }
    console.log('New data added at the end of the file');
})

Basically, we achieved the same result as we did with the fs.appendFile() method:

Content of the firstNote.txt file with text – Result of appendFile method in the firstNote.txt file with the content – Dates: 25/12 - 01/01, Heathrow airport 9:15 AM, need to book a room and rent a car and learn Node.js on the plane

Our old text and the new info got concatenated into one line. However, if you want to break the line, you can use \n for Linux or \r\n for Windows, like here:

const newInfo = ' and learn Node.js on the plane\r\n';

Here are some other flags you might be curious about, all of them are available in the Node.js Docs:

Flag

Description

a

Open file for appending

a+

Open file for reading and appending

r

Open file for reading

r+

Open file for reading and writing

w

Open file for writing

w+

Open file for reading and writing

Conclusion

In this short topic, we shed some light on the basic Node.js methods related to writing files. The easiest way to perform this is to use the fs.writeFile() or fs.appendFile() methods. These functions can be used both synchronously and asynchronously, both of them have optional flag properties to give us more control over tasks we want to do. They are a great tool to work with small data, however, when it comes to larger projects, it is better to stick to the Streams module of Node.js.

11 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo