fs (File System) module in Node.js

In Node.js, you can read a file using the built-in fs (File System) module. There are different ways to read files, depending on your use case:

1. Synchronous Reading (Blocking)

This method blocks the execution until the file is fully read. Suitable for scripts where blocking isn't an issue.

const fs = require('fs');

try {
  const data = fs.readFileSync('file.txt', 'utf8'); // Specify the encoding if you want a string
  console.log(data);
} catch (err) {
  console.error('Error reading file:', err);
}

2. Asynchronous Reading (Non-Blocking)

This method is preferred for non-blocking, scalable applications.

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log(data);
});

3. Using Promises

If you prefer working with promises or async/await, you can use fs.promises:

const fs = require('fs').promises;

async function readFile() {
  try {
    const data = await fs.readFile('file.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

readFile();

4. Reading Large Files (Streaming)

If you're dealing with a large file, using streams is more memory-efficient:

const fs = require('fs');

const stream = fs.createReadStream('file.txt', { encoding: 'utf8' });

stream.on('data', chunk => {
  console.log('Chunk received:', chunk);
});

stream.on('error', err => {
  console.error('Error reading file:', err);
});

stream.on('end', () => {
  console.log('File reading completed.');
});

Choose the Right Method

  • Small files: Use readFileSync or readFile for simplicity.
  • Large files: Use streams to handle memory efficiently.
  • Modern applications: Use promises (fs.promises) or async/await for clean and readable code.

댓글

이 블로그의 인기 게시물

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

how to make inactive kafka topic, 카프카 토픽 비활성화

Screenshot of a web page using Puppeteer with a specific browser width, 웹페이지 스크린샷

리눅스의 부팅과정 (프로세스, 서비스 관리)

To change the ESE index in Fluent Bit

Consume a topic from kafka by Python

ssh-copy-id in ansible

패션 하의, Pants, Skirts, Shorts, Skorts

ftplib.error_perm: 550 Permission denied