Writing Files in Node.js
Writing files is an important operation in Node.js. The File System module allows us to create files and store information inside them using JavaScript code.
For example, a student management application can save student details in a text file. Instead of manually entering the information into a file, we can use Node.js to write the information automatically.
1. What Does Writing a File Mean?
Writing a file means storing information in a file. Node.js
provides the fs.writeFile() method to write data
asynchronously.
If the specified file does not exist, Node.js creates it. If the file already exists, its existing content is replaced by default.
Student details are provided
Writes data to a file
Student details are stored
2. The fs.writeFile() Method
The fs.writeFile() method writes data to a file
asynchronously. It accepts the file path, the data to write,
optional settings, and a callback function.
Syntax:
fs.writeFile(path, data, callback);
Parameters:
| Parameter | Meaning |
|---|---|
path |
The file path where data should be written. |
data |
The string, Buffer, or supported data to write. |
callback |
A function called when the write operation finishes or fails. |
The callback follows the error-first pattern:
(err). If the operation succeeds, the error
parameter is null. If it fails, it contains
error information.
3. First Example: Write a Text File
Let's create a file named message.txt and write
a simple message into it.
Step 1: Create a Project Folder
mkdir WritingFilesDemo
cd WritingFilesDemo
npm init -y
Step 2: Create app.js
const fs = require("fs");
const message = "Welcome to Node.js File Handling!";
fs.writeFile("message.txt", message, (err) => {
if (err) {
console.log("Error writing file:", err.message);
return;
}
console.log("File written successfully!");
});
Step 3: Run the Program
node app.js
Output:
File written successfully!
After the operation succeeds, a file named
message.txt is created in the current working
directory if it did not already exist.
Content of message.txt:
Welcome to Node.js File Handling!
Explanation:
require("fs")imports the File System module.messagestores the text that we want to save.fs.writeFile()writes the message into the file.if (err)checks whether the operation failed.- The success message is displayed only after writing succeeds.
4. Writing Multiple Lines to a File
We can write multiple lines of information into a file by using
the newline character \n.
const fs = require("fs");
const studentDetails =
"Student Name: Rahul\n" +
"Course: Node.js\n" +
"Institute: CIIT Training Institute";
fs.writeFile("student.txt", studentDetails, (err) => {
if (err) {
console.log("Error:", err.message);
return;
}
console.log("Student details saved successfully!");
});
Terminal output:
Student details saved successfully!
Content of student.txt:
Student Name: Rahul
Course: Node.js
Institute: CIIT Training Institute
The \n character starts a new line in the saved
text. Therefore, each student detail appears on a separate line.
5. Important: writeFile() Replaces Existing Content
By default, fs.writeFile() replaces the existing
content of a file. If the file does not exist, it creates the
file.
Example
Suppose message.txt already contains:
Hello Student!
Welcome to our class.
Now execute the following code:
const fs = require("fs");
fs.writeFile("message.txt", "File content updated!", (err) => {
if (err) {
console.log(err.message);
return;
}
console.log("File updated successfully!");
});
Content of message.txt - After:
File content updated!
fs.appendFile(). We will learn that
method in the next lesson.
6. The fs.writeFileSync() Method
The fs.writeFileSync() method writes data
synchronously. The program waits for the write operation to
finish before continuing to the next statement.
Syntax:
fs.writeFileSync(path, data);
Example
const fs = require("fs");
try {
fs.writeFileSync(
"course.txt",
"Course: Node.js\nDuration: 3 Months"
);
console.log("Course details saved successfully!");
} catch (err) {
console.log("Error writing file:", err.message);
}
Output:
Course details saved successfully!
Content of course.txt:
Course: Node.js
Duration: 3 Months
The synchronous method returns after the file has been written.
If the operation fails, it throws an exception, which can be
handled using try...catch.
| Feature | fs.writeFile() | fs.writeFileSync() |
|---|---|---|
| Operation | Asynchronous | Synchronous |
| Completion | Handled through a callback | Returns after writing completes |
| Error handling | Check the callback error | Use try...catch |
| Blocking | Does not block while waiting for the write operation | Blocks further JavaScript execution until writing finishes |
For regular file operations in server applications, asynchronous methods are generally preferred when blocking execution is undesirable.
7. Writing JSON Data to a File
JSON is a common format for storing structured information.
We can convert a JavaScript object into a JSON string using
JSON.stringify() and write that string into a file.
Example
const fs = require("fs");
const student = {
id: 101,
name: "Rahul",
course: "Node.js",
city: "Pune"
};
const jsonData = JSON.stringify(student, null, 4);
fs.writeFile("student.json", jsonData, "utf8", (err) => {
if (err) {
console.log("Error saving student:", err.message);
return;
}
console.log("Student JSON saved successfully!");
});
Output:
Student JSON saved successfully!
Content of student.json:
{
"id": 101,
"name": "Rahul",
"course": "Node.js",
"city": "Pune"
}
Explanation:
studentis a JavaScript object.JSON.stringify()converts the object into JSON text.- The
null, 4arguments format the JSON with indentation. fs.writeFile()stores the JSON text instudent.json.
JSON.stringify() converts
a JavaScript value into JSON text. When reading the JSON file
back into a JavaScript object, use JSON.parse().
8. Understanding File Paths
The path tells Node.js where to create or write a file.
A relative path is resolved from the process's current working
directory, which you can inspect using process.cwd().
const fs = require("fs");
console.log("Current directory:", process.cwd());
fs.writeFile("output.txt", "Hello from Node.js!", (err) => {
if (err) {
console.log("Error:", err.message);
return;
}
console.log("File created in the current working directory.");
});
Example output:
Current directory: C:\Projects\WritingFilesDemo
File created in the current working directory.
The displayed directory will depend on where you run the
application. The file output.txt is written
relative to that working directory.
process.cwd() and verify the destination path.
9. Common Mistakes While Writing Files
| Mistake | Solution |
|---|---|
| Incorrect file path | Check the path and current working directory. |
| Not handling errors | Check the callback error or use try...catch for synchronous operations. |
| Unexpected loss of old content | Remember that writeFile replaces existing content by default. |
| Writing an object directly as JSON | Convert the object using JSON.stringify(). |
| Insufficient file permissions | Check operating-system permissions for the destination. |
| Assuming the write succeeded immediately | Wait for the callback before relying on the completed asynchronous write. |
10. Practice Tasks
Task 1: Create Employee Details
- Create a folder named
EmployeeFileApp. - Initialize the project using
npm init -y. - Create an
app.jsfile. - Write employee ID, name, department, and city into
employee.txt. - Use
fs.writeFile()to save the information. - Handle errors and display a success message.
Expected result: The
employee.txt file should contain all employee
details on separate lines.
Task 2: Save Product Details as JSON
- Create a JavaScript object containing product ID, name, and price.
- Convert the object into formatted JSON using
JSON.stringify(). - Write the JSON text into
product.json. - Handle errors if the operation fails.
- Open the generated file and verify its contents.
Expected result: The
product.json file should contain valid,
formatted JSON data.
Summary
Writing files in Node.js allows applications to store
information on the file system. The
fs.writeFile() method writes data asynchronously,
creates a file when necessary, and replaces existing content
by default. The fs.writeFileSync() method
performs the same general operation synchronously and can
be handled with try...catch.
We also learned how to write multiple lines, save structured
JSON data using JSON.stringify(), understand
file paths, and handle errors. These techniques are useful
for storing student details, employee records, and other
application data in Node.js projects at CIIT Training Institute.