Last updated: Apr 5, 2024
Reading timeยท6 min
To append data to a file using async/await in Node.js:
fs
module from fs/promises
.fs.appendFile()
method to append data to the file.appendFile()
method as it returns a
Promise.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'); });
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.
// ๐๏ธ 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.
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'); });
Notice that we added a newline character \n
at the end of each line.
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
.
// ๐๏ธ 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.
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.
// ... const filePath = './my-folder/my-file.txt'; await fs.appendFile(filePath, 'First line\n', 'utf8'); // ...
You can also use the callback syntax to append data to a file.
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'); });
Notice that we imported the
appendFile()
method from the fs
module, and not fs/promises
.
The method takes the following arguments:
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.
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 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.
You can also append data to a file synchronously in Node.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); }
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.
// ... fs.appendFileSync(filePath, 'First line\r\n', 'utf8'); fs.appendFileSync(filePath, 'Second line\r\n', 'utf8'); fs.appendFileSync(filePath, 'Third line\r\n', 'utf8'); // ...
You can also use a writable stream to append data to a file in Node.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 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.
fs.writeFile()
You can also use the fs.writeFile
method to append data to a file.
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.'); });
Notice that we imported fs
from fs/promises
to use the async/await
syntax.
We passed the following arguments to the fs.writeFile
method:
Notice that the flag
property is set to a
(append).
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.
await fs.writeFile(filePath, 'First line\nSecond Line\n', { flag: 'a+', encoding: 'utf8', });
fs-extra
in Node.jsYou 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.
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.
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.'); });
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.
First line Second line Third line
You can learn more about the related topics by checking out the following tutorials: