fs.writeFileSync() is a method in Node.js used to write data to a file synchronously. It blocks the execution of further code until the file writing operation is completed.
- Writes data to a file and creates the file if it does not exist.
- Overwrites existing content by default (unless flags are specified).
- Being synchronous, it can block the event loop during execution.
Node.js File System (fs) Module
Node.js File System (fs) Module is a built-in module that allows developers to work with the file system on their computer. It provides methods to create, read, update, delete, and manage files and directories.
- Supports both synchronous and asynchronous file operations.
- Used for tasks like reading files, writing files, renaming, deleting, and managing folders.
- Commonly used in server-side applications to handle file storage and data management.
Node.js fs.writeFileSync()
fs.writeFileSync() is a method in the Node.js File System module used to write data to a file synchronously. It ensures that the file writing process is completed before moving to the next line of code.
- Creates a new file if it does not exist.
- Overwrites existing file content by default.
- Blocks the execution (event loop) until the write operation finishes.
Syntax:
fs.writeFileSync( file, data, options )Parameters: This method accepts three parameters as mentioned above and described below:
1. file: It is a string, Buffer, URL, or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similarly to the fs.write() method.
2. data: It is a string, Buffer, TypedArray, or DataView that will be written to the file.
3. options: It is a string or object that can be used to specify optional parameters that will affect the output. It has three optional parameters:
- encoding: It is a string that specifies the encoding of the file. The default value is 'utf8'.
- mode: It is an integer that specifies the file mode. The default value is 0o666.
- flag: It is a string that specifies the flag used while writing to the file. The default value is 'w'.
Features
- Synchronous Operation: Ensures that file writing is completed before moving on to the next operation.
- File Creation and Overwriting: Creates a file if it doesn't exist, or overwrites the file if it does.
- Flexible Data Input: Can handle strings, buffers, and other data types.
- Error Handling: Throws errors for invalid file paths or permission issues.
- Custom Encoding: Supports custom encoding (default is UTF-8).
- File Permissions: Allows you to set file permissions.
Here, we implement the fs.writeFileSync() method in Node.js.
// Filename - index.js
// Node.js program to demonstrate the
// fs.writeFileSync() method
// Import the filesystem module
const fs = require('fs');
let data = "This is a file containing a collection"
+ " of programming languages.\n"
+ "1. C\n2. C++\n3. Python";
fs.writeFileSync("programming.txt", data);
console.log("File written successfully\n");
console.log("The written has the following contents:");
console.log(fs.readFileSync("programming.txt", "utf8"));
Output:
File written successfully
The written has the following contents:
This is a file containing a collection of programming languages.
1. C
2. C++
3. PythonExample 2:Â This appends the names of five movies to a file named "movies.txt" five times and then reads and displays the file's contents.
// Filename - index.js
// Node.js program to demonstrate the
// fs.writeFileSync() method
// Import the filesystem module
const fs = require('fs');
// Writing to the file 5 times
// with the append file mode
for (let i = 0; i < 5; i++) {
fs.writeFileSync("movies.txt",
"Movie " + i + "\n",
{
encoding: "utf8",
flag: "a+",
mode: 0o666
});
}
console.log("File written successfully 5 times\n");
console.log("The written file has the following contents:");
console.log(fs.readFileSync("movies.txt", "utf8"));
Output:
File written successfully 5 times
The written file has the following contents:
Movie 0
Movie 1
Movie 2
Movie 3
Movie 4Example 3: Taking runtime input from users for file name and file data using readline moduleÂ
// Filename - index.js
let readline = require('readline-sync');
let fs = require("fs");
let path = readline.question("Enter file name/path: ");
console.log("Entered path : " + path);
let data = readline.question("Enter file data: ");
//synchronous functions may throw errors
//which can be handled using try-catch block
try {
fs.writeFileSync(path, data, { flag: 'a+' }); //'a+' is append mode
console.log("File written successfully");
} catch (err) {
console.error(err);
}
console.log("-----------------------------------------------");
try {
const data = fs.readFileSync(path, { encoding: "utf8" });
console.log("File content is as follows:");
// Display the file data
console.log(data);
} catch (err) {
console.log(err);
}
OutputÂ

Example 4: Taking runtime input from users for file data using readline module using buffer.
// Filename - index.js
let fs = require("fs");
let readline = require('readline-sync');
let path = readline.question("Enter file name/path: ");
console.log("Entered path : " + path);
// 1024 specifies the buffer size. We can limit
// the data size by this approach
let buf = new Buffer.alloc(1024);
buf = readline.question("Enter data:");
try {
fs.writeFileSync(path, buf, { flag: 'a+' });
console.log("File written successfully");
} catch (err) {
console.error(err);
}
console.log("-----------------------------------------------");
try {
const data = fs.readFileSync(path, { encoding: "utf8" });
console.log("File content is as follows:");
// Display the file data
console.log(data);
} catch (err) {
console.log(err);
}
OutputÂ
