Empowering you to understand your world

How To Write To A File In Node.js

By Nicholas Brown.

Writing files in Node.js can be done asynchronously or synchronously. This article explains how to do both. You can write to a file in Node.js using the FS library, which you won’t have to install. Learning how to do file operations in Node.js is very useful because you can use that to create and maintain configuration files, even if you don’t have a database!

The first step to write to a file is to import the FS module:

const file = require("fs");

You can now use the resulting ‘file’ object to call the ‘writeFile’ method and create a callback function. The asynchronous callback function tells you when the file has been written so that you can take any other steps you need to after the operation is complete. This is useful because you won’t have to use a ‘blocking’ synchronous function that will slow down your app.

The first parameter for the ‘writeFile’ method is the path to the file you want to write to, or just the filename if it is in the same directory as the Node.js file containing this code. The second parameter is the string you want to write to the file. The data type must be a string, so either input a string variable or put hard coded strings in quotes as shown below (‘{“testfield”: “test value”}’).

file.writeFile('config.json', '{"testfield": "test value"}', function(error) {
    if (error) {
    } else {
        console.log('Data written to file.');

The ‘if (error)’ code handles errors and will print out the error to the console if any. The ‘else’ code block will be executed if everything is ok and the operation has been completed. The data being written above happens to be JSON, but it can be any string you wish. JSON just happens to be widely used.

Writing A File Synchronously

You can write a file synchronously using even fewer lines of code as shown below. However, note that this will slow down your app. This should only be used if you have to block the app from continuing execution until the file has been written.

const file = require('fs');
file.writeFileSync("myfile.txt", "Look for this string in the file");
console.log('File written successfully.');

Further Reading

How To Read Files Using Node.js

Subscribe to our newsletter
Get notified when new content is published