클라이언트 측(브라우저)에서는 JS에서 파일을 읽거나 쓸 수 없습니다. 이것은 Node.js의 fs 모듈을 사용하여 서버 측에서 수행할 수 있습니다. 파일 시스템에서 파일을 읽고 쓰는 동기화 및 비동기 기능을 제공합니다. node.js의 fs 모듈을 사용하여 파일을 읽고 쓰는 예를 살펴보겠습니다.
다음 코드를 포함하는 main.js라는 js 파일을 생성해 보겠습니다. -
var fs = require("fs");
console.log("Going to write into existing file");
// Open a new file with name input.txt and write Simply Easy Learning! to it.
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
// Read the newly written file and print all of its content on the console
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}); 이제 main.js를 실행하여 결과를 확인하십시오 -
$ node main.js
출력
Going to write into existing file Data written successfully! Let's read newly written data Asynchronous read: Simply Easy Learning!
fs 모듈이 노드에서 작동하는 방식과 사용 방법에 대한 자세한 내용은 https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm에서 확인할 수 있습니다.