파일로 출력하기 - fs.writeFile()
1 2 3 4 | const fs = require('fs'); const contents = 'hello\nbye\n안녕'; fs.writeFile('./message.txt', contents); | cs |
동기로 파일 열기 - fs.readFileSync()
1 2 3 4 5 6 | const fs = require('fs'); const data = fs.readFileSync('./message.txt'); const string = data.toString(); console.log('sync work01'); console.log(string); | cs |
비동기로 파일 열기 - fs.readfile()
1 2 3 4 5 6 7 | const fs = require('fs'); fs.readFile('./message.txt', (err, data) => { if (err) throw err; console.log('async work01'); console.log(data.toString()); }); | cs |
파일 내용 수정하기
1 2 3 4 5 6 7 8 | const fs = require('fs'); fs.readFile('./message.txt', (err, data) => { if (err) throw err; let contents = data.toString(); contents = 'replaced'; fs.writeFile('./message.txt', contents); }); | cs |
파일에 내용 수정하기 - fs.appendFile()
1 2 3 4 5 | const fs = require('fs'); const list = [1, 2, 3, 4, 5]; list.forEach(item => fs.appendFile('./chapters.txt', `chapter ${item}\n`)); | cs |
디렉토리 만들기 fs.mkdirSync()
1 2 3 4 5 6 7 | const fs = require('fs'); const dirName = `${__dirname}/img`; if (!fs.existsSync(dirName)) { fs.mkdirSync(dirName); } | cs |
파일 리스트 출력하기
1 2 3 4 5 6 7 8 | const testFolder = './'; const fs = require('fs'); const filenameList = fs.readdirSync(testFolder); filenameList.forEach((fileName) => { console.log(fileName); }); | cs |
list를 json 형식으로 파일에 저장하기 - JSON.stringify()
1 2 3 4 5 6 7 8 | const fs = require('fs'); const userList = [ { name: 'kyeongrok', age: 31 }, { name: 'jihyun', age: 31 }, ]; fs.writeFile('./list.json', JSON.stringify(userList)); | cs |
파일을 json 형식으로 불러오기 - JSON.parse()
1 2 3 4 5 6 7 8 | const fs = require('fs'); fs.readFile('./list.json', (err, data) => { if (err) throw err; const json = JSON.parse(data.toString()); console.log('name:', json[0].name); console.log('name:', json[1].name); }); | cs |
파일 이름 바꾸기
1 2 3 4 5 6 7 8 9 10 11 12 | const fs = require('fs'); const renameFile = (fromFilePathName, toFilePathName) => { fs.rename(fromFilePathName, toFilePathName, (err) => { if (err) console.log(`ERROR: ${err}`); }); }; const fromFilePathName = './hello.txt'; const toFilePathName = './bye.txt'; renameFile(fromFilePathName, toFilePathName); | cs |
'공부 > Node.js' 카테고리의 다른 글
템플릿 엔진 모듈 - ejs, pug 모듈 (0) | 2019.03.07 |
---|---|
크롤링 - cheerio, iconv-lite 모듈 (1) | 2019.03.07 |
npm (0) | 2019.03.06 |
http 모듈 (0) | 2019.03.06 |
API 읽는 법 - fs.access(path[,mode],callback) (0) | 2019.03.06 |