1. 개요

const fs = require('node:fs');
fs.stat('/Users/joe/test.txt', (err, stats) => {
  if (err) {
    console.error(err);
  }
  // we have access to the file stats in `stats`
});

2. 파일 페스 | Node.js File Paths

3. 파일읽기

3-1. Stream 예시

import fs from 'fs';
import { pipeline } from 'node:stream/promises';
import path from 'path';

const fileUrl = '<https://www.gutenberg.org/files/2701/2701-0.txt>';
const outputFilePath = path.join(process.cwd(), 'moby.md');

async function downloadFile(url, outputPath) {
  const response = await fetch(url);

  if (!response.ok || !response.body) {
    // consuming the response body is mandatory: <https://undici.nodejs.org/#/?id=garbage-collection>
    await response.body?.cancel();
    throw new Error(`Failed to fetch ${url}. Status: ${response.status}`);
  }

  const fileStream = fs.createWriteStream(outputPath);
  console.log(`Downloading file from ${url} to ${outputPath}`);

  await pipeline(response.body, fileStream);
  console.log('File downloaded successfully');
}

async function readFile(filePath) {
  const readStream = fs.createReadStream(filePath, { encoding: 'utf8' });

  try {
    for await (const chunk of readStream) {
      console.log('--- File chunk start ---');
      console.log(chunk);
      console.log('--- File chunk end ---');
    }
    console.log('Finished reading the file.');
  } catch (error) {
    console.error(`Error reading file: ${error.message}`);
  }
}

try {
  await downloadFile(fileUrl, outputFilePath);
  await readFile(outputFilePath);
} catch (error) {
  console.error(`Error: ${error.message}`);
}

4. 파일 쓰기

4.1 가장 간단한 파일 쓰기

const fs = require('node:fs');

const content = 'Some content!';

fs.writeFile('/Users/joe/test.txt', content, err => {
  if (err) {
    console.error(err);
  } else {
    // file written successfully
  }
});

try {
  fs.writeFileSync('/Users/joe/test.txt', content);
  // file written successfully
} catch (err) {
  console.error(err);
}
const fs = require('node:fs/promises');
async function example() {
  try {
    const content = 'Some content!';
    await fs.writeFile('/Users/joe/test.txt', content);
  } catch (err) {
    console.log(err);
  }
}
example();

Flag

fs.writeFile('/Users/joe/test.txt', content, { flag: 'a+' }, err => {});

Flag  국기/플래그 Description  설명 File gets created if it doesn't exist파일이 존재하지 않는 경우에는 새로 생성됩니다.
r+ This flag opens the file for reading and writing이 플래그를 사용하면 해당 파일을 읽기 및 쓰기 위해 열 수 있습니다. ❌
w+ This flag opens the file for reading and writing and it also positions the stream at the beginning of the file이 플래그를 사용하면 파일을 읽고 쓸 수 있게 되며, 동시에 스트림의 위치도 파일의 시작 부분으로 이동합니다. ✅
a This flag opens the file for writing and it also positions the stream at the end of the file이 플래그를 사용하면 파일을 쓰기 모드로 열 수 있으며, 스트림의 위치도 파일의 끝으로 이동합니다. ✅
a+ This flag opens the file for reading and writing and it also positions the stream at the end of the file이 플래그를 사용하면 파일을 읽고 쓸 수 있게 되며, 동시에 스트림의 위치도 파일의 끝으로 이동합니다. ✅