Node.JS Write to File
We can write data to file in Node.js using fs module.
In this tutorial, we will learn how to use fs module and its function writeFile() to write content to a file.
The fs.writeFile() method writes data asynchronously. It creates the file if it does not exist, and it replaces the existing file content by default when the same file path already exists. For many scripts, this is the simplest way to save text, JSON, or buffer data to a file.
- Syntax of fs.writeFile() in Node.js
- Example 1 – Write data to a text file
- Example 2 – Write content with specified encoding
- Write a file using fs.promises in Node.js
- Overwrite, append, and avoid replacing an existing file
- FAQs on writing files in Node.js
Syntax – writeFile()
The syntax of writeFile() function is
fs = require('fs');
fs.writeFile(filename, data, [encoding], [callback_function])
where
- filename : [mandatory] name of the file, the data has to be written to
- data : [mandatory] content that has to be written to file
- encoding : [optional] encoding standard that has to be followed while writing content to file.
- callback_function : [optional] function that would be called once writing to the file is completed
Common encoding examples are
- ascii
- utf8
- base64
Note : A new file with specified filename is created with data specified. If a file with the same name exists already, the content is overwritten. Care has to be taken as previous content of file could be lost.
In current Node.js code, the same method is commonly written with an options object. This makes encoding and file flags clearer.
const fs = require('fs');
fs.writeFile(filePath, data, { encoding: 'utf8', flag: 'w' }, callback);
The default flag is w, which means write the file and truncate existing content. Use this default only when replacing the old content is acceptable.
Example 1 – Write data to file in Node.js
In this example, we shall write content, “Hello !” , to a text file sample.txt.
nodejs-write-to-file-example.js
// include file system module
var fs = require('fs');
var data = "Hello !"
// write data to file sample.html
fs.writeFile('sample.txt', data,
// callback function that is called after writing file is done
function(err) {
if (err) throw err;
// if no error
console.log("Data is written to file successfully.")
});
When the above program is run in Terminal or Command Prompt, you will get the following output.
Output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example.js
Data is written to file successfully.
After the script runs, sample.txt contains the text written from the data variable. If the file already had content, that content is replaced by Hello !.
Example 2 – Write Content to File with Specified Encoding
We can also specify encoding to be followed by writeFile() method when it writes content to file.
In this example, we will tell writeFile() method to write content to file with ASCII encoding.
nodejs-write-to-file-example-2.js
// include file system module
var fs = require('fs');
var data = "HELLO";
// write data to file sample.html
fs.writeFile('sample.txt',data, 'ascii',
// callback function that is called after writing file is done
function(err) {
if (err) throw err;
// if no error
console.log("Data is written to file successfully.")
});
When the above program is run in Terminal,
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example-2.js
Data is written to file successfully.
For normal text files, utf8 is the usual encoding. Use ascii only when the content is limited to ASCII characters and your use case specifically requires that encoding.
Handle errors when writing a file with fs.writeFile()
The callback receives an error object when Node.js cannot write the file. Common reasons include a missing directory, insufficient permissions, an invalid path, or a disk-related problem. Instead of ignoring the error, check it before reporting success.
const fs = require('fs');
const filePath = 'logs/app.txt';
const data = 'Application started\n';
fs.writeFile(filePath, data, 'utf8', function (err) {
if (err) {
console.error('Unable to write file:', err.message);
return;
}
console.log('File written successfully.');
});
This example prints a useful error message and stops the callback with return. That prevents the success message from running after a failed write.
Write a file using fs.promises in Node.js
When your Node.js project uses async and await, the promise-based file system API is often easier to read than nested callbacks. The fs/promises module provides a promise version of writeFile().
const fs = require('fs/promises');
async function saveMessage() {
try {
await fs.writeFile('message.txt', 'Hello from Node.js\n', 'utf8');
console.log('message.txt written successfully.');
} catch (err) {
console.error('Unable to write file:', err.message);
}
}
saveMessage();
The promise-based form is still asynchronous. It does not block the event loop while the file operation is pending, and the try...catch block handles write errors.
$ node write-message.js
message.txt written successfully.
Overwrite, append, and avoid replacing an existing file in Node.js
By default, fs.writeFile() overwrites the target file. If you need a different behavior, choose the proper method or file flag before writing.
| Node.js file writing need | Recommended method or flag | Behavior |
|---|---|---|
| Write new content and replace old content | fs.writeFile(file, data) | Creates the file if needed and truncates existing content. |
| Add content to the end of a file | fs.appendFile(file, data) | Creates the file if needed and appends without removing old content. |
| Fail if the file already exists | fs.writeFile(file, data, { flag: 'wx' }) | Writes only when the path does not already exist. |
| Write small setup files during startup | fs.writeFileSync(file, data) | Writes synchronously and blocks until finished. |
The following example appends a new line to an existing log file without deleting previous lines.
const fs = require('fs');
const logLine = `${new Date().toISOString()} - user logged in\n`;
fs.appendFile('app.log', logLine, 'utf8', function (err) {
if (err) {
console.error('Unable to append to file:', err.message);
return;
}
console.log('Log line appended.');
});
The next example uses the wx flag so the write fails when the file already exists. This is useful when accidental overwrite must be avoided.
const fs = require('fs');
fs.writeFile('report.txt', 'First report\n', { encoding: 'utf8', flag: 'wx' }, function (err) {
if (err) {
console.error('File was not written:', err.message);
return;
}
console.log('report.txt created.');
});
Write JSON data to a file in Node.js
To write an object to a JSON file, convert the object to a JSON string first. Use JSON.stringify() and include indentation when you want the file to be readable.
const fs = require('fs/promises');
async function writeJsonFile() {
const user = {
id: 101,
name: 'Ravi',
active: true
};
const jsonData = JSON.stringify(user, null, 2);
try {
await fs.writeFile('user.json', jsonData, 'utf8');
console.log('user.json written successfully.');
} catch (err) {
console.error('Unable to write JSON file:', err.message);
}
}
writeJsonFile();
The generated JSON file contains formatted JSON text.
{
"id": 101,
"name": "Ravi",
"active": true
}
Create the folder before writing a file in Node.js
fs.writeFile() creates the file, but it does not automatically create missing parent folders. If the directory does not exist, create it first with mkdir() and the recursive option.
const fs = require('fs/promises');
const path = require('path');
async function writeFileInFolder() {
const folder = 'reports';
const filePath = path.join(folder, 'daily-report.txt');
try {
await fs.mkdir(folder, { recursive: true });
await fs.writeFile(filePath, 'Daily report content\n', 'utf8');
console.log(`${filePath} written successfully.`);
} catch (err) {
console.error('Unable to write report:', err.message);
}
}
writeFileInFolder();
This pattern is useful when writing generated reports, export files, log files, or output files inside a folder that may not exist yet.
When to use writeFileSync() in Node.js
fs.writeFileSync() writes a file synchronously. It is simple, but it blocks the current thread until the write operation finishes. Use it only when blocking is acceptable, such as in small scripts, build steps, setup tasks, or command-line utilities.
const fs = require('fs');
try {
fs.writeFileSync('sync-output.txt', 'Written with writeFileSync\n', 'utf8');
console.log('sync-output.txt written successfully.');
} catch (err) {
console.error('Unable to write file:', err.message);
}
For web servers and applications handling many requests, prefer asynchronous fs.writeFile() or fs.promises.writeFile() so file operations do not block other work.
Common mistakes while writing files in Node.js
- Forgetting that writeFile overwrites content: Use
appendFile()or the right file flag when old content must be preserved. - Ignoring the callback error: Always check
errbefore printing a success message. - Trying to write into a missing folder: Create the parent directory first with
fs.mkdir()orfs.promises.mkdir(). - Using synchronous writes in a server request path: Prefer asynchronous writes for server-side request handling.
- Writing JavaScript objects directly: Convert objects with
JSON.stringify()before writing JSON files.
QA checklist for a Node.js write-to-file tutorial
- Show the callback-based
fs.writeFile()example for beginners. - Explain that
fs.writeFile()overwrites an existing file by default. - Include error handling for failed writes, missing folders, and permission problems.
- Use
fs.promises.writeFile()for anasync/awaitexample. - Separate overwrite, append, and “do not overwrite existing file” use cases.
- Use
JSON.stringify()before writing object data to a JSON file.
FAQs on Node.js write to file
How do I write text to a file in Node.js?
Use fs.writeFile(filePath, data, callback) or fs.promises.writeFile(filePath, data). Pass the file path, the text to write, and handle any error returned by the callback or promise.
Does fs.writeFile create a file if it does not exist?
Yes. fs.writeFile() creates the target file when the parent directory exists. If the parent directory is missing, the write fails unless you create the folder first.
Does fs.writeFile overwrite an existing file?
Yes. By default, fs.writeFile() replaces the existing file content. Use fs.appendFile() to add content, or use a flag such as wx when you want the write to fail if the file already exists.
What is the difference between fs.writeFile and fs.writeFileSync?
fs.writeFile() is asynchronous and uses a callback. fs.writeFileSync() is synchronous and blocks until the write finishes. Use asynchronous writes for applications and synchronous writes only when blocking is acceptable.
How do I write JSON data to a file in Node.js?
Convert the JavaScript object with JSON.stringify(object, null, 2), then write the resulting string with fs.writeFile() or fs.promises.writeFile().
Conclusion: writing files with Node.js fs.writeFile()
In this Node.js Tutorial – Node FS – Write to File, we have learnt to write content to file with the help of an example. Use fs.writeFile() for callback-based asynchronous writing, fs.promises.writeFile() with async/await, appendFile() when old content must be preserved, and writeFileSync() only when a blocking write is acceptable.
TutorialKart.com