WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Basic · question 8 of 100

How can you read and write files using Node.js?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

In Node.js, you can read and write files using the built-in ‘fs‘ module (short for "file system"). The ‘fs‘ module provides several asynchronous and synchronous methods for working with the file system.

Here’s a detailed explanation of how to read and write files in Node.js using the ‘fs‘ module:

**1. Import the ‘fs‘ module:**

Before working with files, you need to import the ‘fs‘ module using the ‘require‘ function:

const fs = require('fs');

**2. Read a file:**

To read a file in Node.js, you can use either the asynchronous ‘fs.readFile‘ method or the synchronous ‘fs.readFileSync‘ method.

a) *Asynchronous*:

fs.readFile('path/to/your/file.txt', 'utf-8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});

b) *Synchronous*:

try {
  const data = fs.readFileSync('path/to/your/file.txt', 'utf-8');
  console.log('File content:', data);
} catch (err) {
  console.error('Error reading file:', err);
}

**3. Write a file:**

To write a file in Node.js, you can use either the asynchronous ‘fs.writeFile‘ method or the synchronous ‘fs.writeFileSync‘ method.

a) *Asynchronous*:

const content = 'This is the text that will be written to the file.';

fs.writeFile('path/to/your/output.txt', content, (err) => {
  if (err) {
    console.error('Error writing file:', err);
    return;
  }
  console.log('File has been written successfully.');
});

b) *Synchronous*:

const content = 'This is the text that will be written to the file.';

try {
  fs.writeFileSync('path/to/your/output.txt', content);
  console.log('File has been written successfully.');
} catch (err) {
  console.error('Error writing file:', err);
}

The above examples demonstrate how you can read and write files using Node.js and the ‘fs‘ module. Remember that using synchronous methods will block the Node.js event loop, so it’s generally better to use asynchronous methods when working with files in a non-blocking way.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics