Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

Node.js Application

Student details are provided

↓
fs.writeFile()

Writes data to a file

↓
student.txt

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:

JavaScript
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

Terminal
mkdir WritingFilesDemo
cd WritingFilesDemo
npm init -y

Step 2: Create app.js

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

Terminal
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:

message.txt
Welcome to Node.js File Handling!

Explanation:

  • require("fs") imports the File System module.
  • message stores 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.

app.js
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.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:

message.txt - Before
Hello Student!
Welcome to our class.

Now execute the following code:

app.js
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:

message.txt
File content updated!
Important: The original two lines are replaced. If you want to preserve existing content and add new content at the end, use 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:

JavaScript
fs.writeFileSync(path, data);

Example

app.js
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.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

app.js
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:

student.json
{
    "id": 101,
    "name": "Rahul",
    "course": "Node.js",
    "city": "Pune"
}

Explanation:

  • student is a JavaScript object.
  • JSON.stringify() converts the object into JSON text.
  • The null, 4 arguments format the JSON with indentation.
  • fs.writeFile() stores the JSON text in student.json.
Remember: 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().

app.js
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.

Tip: If Node.js reports that a file cannot be written or you cannot find the generated file, check 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

  1. Create a folder named EmployeeFileApp.
  2. Initialize the project using npm init -y.
  3. Create an app.js file.
  4. Write employee ID, name, department, and city into employee.txt.
  5. Use fs.writeFile() to save the information.
  6. 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

  1. Create a JavaScript object containing product ID, name, and price.
  2. Convert the object into formatted JSON using JSON.stringify().
  3. Write the JSON text into product.json.
  4. Handle errors if the operation fails.
  5. 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.