728x90
fs모듈
fs는 Node.js에서 기본적으로 제공하는 모듈로 File System의 약자이다.
파일을 읽기, 쓰기 등의 작업을 할 수 있다.
파일 읽기
fs.readFile과 fs.readFileSync로 파일을 읽어올 수 있다.
fs.readFileSync는 동기적으로 파일을 읽어오고
fs.readFile은 비동기적으로 파일을 읽어온다.
fs.readFileSync
readFileSync은 다음과 같은 형태로 사용한다.
fs.readFileSync(path[, options])
테스트할 파일을 하나 만들어보자. 파일명은 test.txt로 하고 내용은 Hello Node.js로 채웠다.
// test.txt
Hello Node.js
const fs = require("fs");
let input = fs.readFileSync("./test.txt").toString();
console.log(input);
console.log("읽어오기 완료");
// Hello Node.js
// 읽어오기 완료
코드를 실행하면 Hello Node.js -> 읽어오기 완료 순으로 콘솔에 출력이 된다.
동기적으로 실행되기 때문에 위에서 아래로 순서대로 실행하고 출력한다.
fs.readFile
readFile는 다음과 같은 형태로 사용한다.
fs.readFile(path[, options], callback)
test.txt를 위에랑 똑같이 하나 만들었다.
// test.txt
Hello Node.js
// app.js
const fs = require("fs");
fs.readFile("./test.txt", (err, data) => {
console.log(data.toString());
});
console.log("읽어오기 완료");
// 읽어오기 완료
// Hello Node.js
readFile로 만들면 비동기적으로 파일을 읽어오기 때문에 test.txt파일을 읽어올 때에도 app.js가 계속 실행되기 때문에 실행순서가 동기적으로 처리된 것과 다르게 나온다.
728x90
반응형
'Web > Node.js' 카테고리의 다른 글
[Node.js] express.static (0) | 2021.09.09 |
---|---|
[Node.js] Express (0) | 2021.09.09 |
[Node.js] path, __dirname, __filename (0) | 2021.09.09 |
[Node.js] morgan (0) | 2021.09.06 |
[Node.js] REPL (0) | 2021.09.01 |