Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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) {
        console.log(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