How to append data to a File using Node.js [6 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
6 min

banner

# Table of Contents

  1. How to append data to a File using Async/Await using Node.js
  2. Append data to a file using callbacks in Node.js
  3. How to append data to a File synchronously using Node.js
  4. Appending data to a file using a writable stream in Node.js
  5. Appending data to a file using fs.writeFile()
  6. Append data to a file using fs-extra in Node.js

# How to append data to a File using Async/Await using Node.js

To append data to a file using async/await in Node.js:

  1. Import the fs module from fs/promises.
  2. Use the fs.appendFile() method to append data to the file.
  3. Make sure to await each call to the appendFile() method as it returns a Promise.
index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') async function appendDataToFile() { try { const filePath = 'my-file.txt'; await fs.appendFile(filePath, 'First line\n', 'utf8'); await fs.appendFile(filePath, 'Second line\n', 'utf8'); await fs.appendFile(filePath, 'Third line\n', 'utf8'); } catch (err) { console.log(err.message); } } appendDataToFile().then(() => { console.log('Data appended to the file'); });

contents of file

The code for this article is available on GitHub

Notice that we imported the fs module from fs/promises to be able to use the async equivalent of the fs methods.

The example above uses the ES6 modules import/export syntax.

If you use CommonJS require(), use the following import statement instead.

index.js
// ๐Ÿ‘‡๏ธ if you use CommonJS require() const fs = require('fs/promises')

The fsPromises.appendFile() method takes the file path, the data and the encoding as arguments.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') async function appendDataToFile() { try { const filePath = 'my-file.txt'; await fs.appendFile(filePath, 'First line\n', 'utf8'); await fs.appendFile(filePath, 'Second line\n', 'utf8'); await fs.appendFile(filePath, 'Third line\n', 'utf8'); } catch (err) { console.log(err.message); } } appendDataToFile().then(() => { console.log('Data appended to the file'); });
The code for this article is available on GitHub

Notice that we added a newline character \n at the end of each line.

index.js
await fs.appendFile(filePath, 'First line\n', 'utf8');

This ensures that the data that is appended with each call of the fs.appendFile() method starts on a new line.

If you are on Windows, you might have to use \r\n instead of \n.

index.js
// ๐Ÿ‘‡๏ธ on Windows (if \n didn't work) await fs.appendFile(filePath, 'First line\r\n', 'utf8'); await fs.appendFile(filePath, 'Second line\r\n', 'utf8'); await fs.appendFile(filePath, 'Third line\r\n', 'utf8');

You can also use the os.EOL property to get the operating system-specific end-of-line character.

index.js
import os from 'os'; console.dir(os.EOL); // ๐Ÿ‘‰๏ธ \n

The property returns \n on macOS and Linux and \r\n on Windows.

If an error occurs when appending data to the file, it gets passed to the catch() method.

You can also pass a file path to the fs.appendFile() method, it doesn't have to be a file name.

index.js
// ... const filePath = './my-folder/my-file.txt'; await fs.appendFile(filePath, 'First line\n', 'utf8'); // ...

# Append data to a file using callbacks in Node.js

You can also use the callback syntax to append data to a file.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') const filePath = 'my-file.txt'; fs.appendFile(filePath, 'First line\n', 'utf8', err => { if (err) { throw err; } console.log('Line appended to file'); });
The code for this article is available on GitHub

Notice that we imported the appendFile() method from the fs module, and not fs/promises.

The method takes the following arguments:

  1. The path to the file.
  2. The data you want to append to the file.
  3. The encoding.
  4. A callback that gets called with an error (if one has occurred).

If no error has occurred, the err variable will be null.

If you need to call the fs.appendFile() multiple times when using callbacks, you have to nest the calls.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') const filePath = 'my-file.txt'; // 1) First call to appendFile fs.appendFile(filePath, 'First line\n', 'utf8', err => { if (err) { throw err; } console.log('Line appended to file'); // 2) Second call to appendFile fs.appendFile(filePath, 'Second line\n', 'utf8', err => { if (err) { throw err; } console.log('Next line appended to file'); }); });
The code for this article is available on GitHub

The first call to appendFile() runs and the string First line\n is asynchronously appended to the file.

Assuming no error occurs, then the second call to appendFile() runs.

Then the string Second line\n is appended to the file.

append multiple lines to file using callbacks

# How to append data to a File synchronously using Node.js

You can also append data to a file synchronously in Node.js.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') const filePath = 'my-file.txt'; try { fs.appendFileSync(filePath, 'First line\n', 'utf8'); fs.appendFileSync(filePath, 'Second line\n', 'utf8'); fs.appendFileSync(filePath, 'Third line\n', 'utf8'); } catch (err) { console.log(err.message); }
The code for this article is available on GitHub

We passed the file path, the data we want to append to the file and the encoding to the fs.appendFileSync() method.

If an error occurs while appending the data to the file, it gets passed to the catch() method.

If you are on Windows and the \n character doesn't append each string on a new line, try using the \r\n characters instead.

index.js
// ... fs.appendFileSync(filePath, 'First line\r\n', 'utf8'); fs.appendFileSync(filePath, 'Second line\r\n', 'utf8'); fs.appendFileSync(filePath, 'Third line\r\n', 'utf8'); // ...

# Appending data to a file using a writable stream in Node.js

You can also use a writable stream to append data to a file in Node.js.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') const filePath = 'my-file.txt'; try { const stream = fs.createWriteStream(filePath, {flags: 'a'}); stream.write('First line\n', 'utf8'); stream.write('Second line\n', 'utf8'); stream.write('Third line\n', 'utf8'); stream.end(); } catch (err) { console.log(err.message); }
The code for this article is available on GitHub

The fs.createWriteStream() method creates a writable stream.

Notice that we set the flags property to a (append).

If the flags property is set to w, then the file is truncated (its contents are deleted) before writing to it.

You can use the write() method on the stream to append data to the file.

Once you're done, call the close() method to close the file descriptor.

# Appending data to a file using fs.writeFile()

You can also use the fs.writeFile method to append data to a file.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') async function appendDataToFile() { const filePath = 'my-file.txt'; try { await fs.writeFile(filePath, 'First line\nSecond Line\n', { flag: 'a', encoding: 'utf8', }); console.log('Data appended to the file'); } catch (err) { console.log(err.message); } } appendDataToFile().then(() => { console.log('Runs after the data is appended to the file.'); });
The code for this article is available on GitHub

Notice that we imported fs from fs/promises to use the async/await syntax.

We passed the following arguments to the fs.writeFile method:

  1. The file path.
  2. The data we want to append to the file.
  3. An options object.

Notice that the flag property is set to a (append).

index.js
await fs.writeFile(filePath, 'First line\nSecond Line\n', { flag: 'a', encoding: 'utf8', });

If you need to open the file for appending and create the file if it doesn't already exist, use the a+ flag.

index.js
await fs.writeFile(filePath, 'First line\nSecond Line\n', { flag: 'a+', encoding: 'utf8', });

# Append data to a file using fs-extra in Node.js

You can also append data to a file by using the popular fs-extra module.

First, make sure you have the module installed.

Open your terminal in your project's root directory and run the following commands.

shell
npm init -y # install with NPM npm install fs-extra # or with YARN yarn add fs-extra

Import and use the fs-extra module as follows.

index.js
import fs from 'fs-extra'; import os from 'os'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const os = require('os') // const fs = require('fs-extra') async function appendDataToFile() { const filePath = 'my-file.txt'; try { await fs.outputFile(filePath, `First line${os.EOL}`, { flag: 'a', }); await fs.outputFile(filePath, `Second line${os.EOL}`, { flag: 'a', }); await fs.outputFile(filePath, `Third line${os.EOL}`, { flag: 'a', }); console.log('Data appended to the file'); } catch (err) { console.log(err.message); } } appendDataToFile().then(() => { console.log('Runs after the data is appended to the file.'); });
The code for this article is available on GitHub

Notice that we used the os.EOL property instead of the \n character.

The property returns the operating system-specific end-of-line character (\n on macOS and Linux and \r\n on Windows).

We set the flag property to a (append) in the options object to append data to the file.

Running the node index.js command produces a my-file.txt text file with the following contents.

my-file.txt
First line Second line Third line

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev