node v18
텍스트 파일을 읽기 위해 nodejs 에서는 readFile, readFileSync 가 있다.
1. async/await readFile
import { readFile } from 'node:fs/promises';
const path = 'YOUR_TEXT_FILE_PATH';
try {
const text = await readFile(path, 'utf8');
console.log(text);
} catch (err) {
console.log(err);
}
2. Callback readFile
import { readFile } from 'node:fs';
const path = 'YOUR_TEXT_FILE_PATH';
readFile(path, 'utf8', (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
3. readFileSync
import { readFileSync } from 'node:fs';
const path = 'YOUR_TEXT_FILE_PATH';
const text = readFileSync(path, 'utf8');
console.log(text);
'Programming > Nodejs tips' 카테고리의 다른 글
Nodejs 비밀번호 암호화 (0) | 2022.11.18 |
---|---|
Nodejs + Express + Typescript 프로젝트 세팅 (0) | 2022.11.17 |