[npm] file-system 사용하여 파일/폴더 작업하기
https://www.npmjs.com/package/file-system
file-system
Strengthen the ability of file system. Latest version: 2.2.2, last published: 6 years ago. Start using file-system in your project by running `npm i file-system`. There are 402 other projects in the npm registry using file-system.
www.npmjs.com
위의 링크에서 보면 첫 소개로 아래와 같이 나온다.
This module make file opertaion apis simple, you don't need to care the dir exits. and the api is same as node's filesystem. This is no exists time cost for this plugin.
(이 모듈은 파일 작업 API를 간단하게 만들어 dir 종료를 신경 쓸 필요가 없습니다.
API는 노드의 파일 시스템과 동일합니다.)
일단 내가 이 모듈을 쓰는 이유는
지금 하는 프로젝트에서 무언가 데이터를 json 형태로 받아와서 (또는 어떤 형태로든) 이를 데이터베이스에 추가하는것이 아니라 로컬에 파일 시스템으로 저장하기 위해서이다.
1. 설치
터미널에 아래와 같이 입력하여 설치한다.
npm install file-system
2. 파일시스템을 사용할 서버(node.js)에 아래와 같이 선언을 해준다.
const fs = require('fs');
3. 사용할 메서드르? 기능? 을 아래와 같이 적용하여 사용한다.
(자세한 사용법은 위의 링크에서 확인한다.)
(나는 파일 생성을 사용할 것이다. --> node의 writefile과 동일하다고 하여 아래 링크로 찾아보았다.)
https://nodejs.org/api/fs.html#fswritefilefile-data-options-callback
File system | Node.js v18.7.0 Documentation
nodejs.org
fs.writeFile(file, data[, options], callback)
ex) writeFile('message.txt', 'Hello Node.js', utf8, callback);
위와 같은 식으로
처음인자로 경로와 파일명과 확장자
두번째는 내용
세번째는 옵션
네번째는 콜백함수를 받는 듯 하다.
const express = require('express');
const fs = require('fs');
const router = express.Router();
let flow = [];
router.post('/', (req, res) => {
console.log(req.body);
flow = req.body;
fs.writeFile("./writeFileDir/test.txt", JSON.stringify(flow), (err) => {
if (err) throw err;
console.log("파일 저장 완료");
})
return res.send('성공');
});
router.get('/', (req, res) => {
res.json(flow);
});
module.exports = router;
위와 같이 했더니 server 폴더 안에 writeFileDir 폴더 안에 test.txt로 파일이 생성되었다.
파일 읽어오는 방법.
fs.readFile(path[, options], callback)
readFile로 파일을 읽어온다.
인자로는 경로랑 옵션, 콜백이 있는듯 하다.
아래와 같이 작성해보았다.
const file = fs.readFileSync('./writeFileDir/test.json', 'utf8', (err) => {
if (err) throw err;
console.log(file);
});
위와 같이 하면 file에 string으로 내용이 담긴다.
콜백함수는 안 써주면 에러가 난다.