Programming/Nodejs tips
Nodejs 로 텍스트 파일 가져오기
우동개
2022. 11. 16. 18:28
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);