Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Node.js Reading & Writing Files
Node.js Intermediate FREE

Reading & Writing Files

Lesson 1 of 17 Intermediate Interactive

The fs module lets you read, write, and manipulate files.

Syntax

NODEJS
const fs = require('fs');

// Read file
const data = fs.readFileSync('file.txt', 'utf8');

// Write file
fs.writeFileSync('output.txt', 'Hello World');
File System Operations
NODE
const fs = require("fs");

// Write file
fs.writeFileSync("example.txt", `Hello, Node.js!
Line two`);

// Read file
const content = fs.readFileSync("example.txt", "utf-8");
console.log(content);

// Async read
fs.readFile("example.txt", "utf-8", (err, data) => {
    if (err) throw err;
    console.log(data);
});

Practice

1
Exercise

Practice this concept.

Answer
Write the code as shown above.

Quick Quiz

1

What did you learn?

This covers the basics.

Interview Questions

It is a fundamental Node.js feature.