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`
});
fs.readFile() 기본 (비동기), fs.readFileSync() (동기), await fs.readFile() 가능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}`);
}
await pipeline(response.body, fileStream); 로 연결할 수 있다.pipeline 은 입출력을 맞추면 몇개고 stream 을 연결할 수 있다.
예시
pipeline(
readable,
gzip,
encrypt,
writable
)
Readable
→ Duplex/Transform
→ Duplex/Transform
→ Writable
Readable: 읽기만 가능
Writable: 쓰기만 가능
Duplex: 읽기/쓰기 둘 다 가능
Transform: 입력 받아 변환 후 출력
Transform ⊂ Duplex
writeFile fs.writeFileSync() fsPromises.writeFile()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();
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이 플래그를 사용하면 파일을 읽고 쓸 수 있게 되며, 동시에 스트림의 위치도 파일의 끝으로 이동합니다. | ✅ |