반응형

File System 함수를 node js에 가져오는 방법은 require('fs'); 이다.

◎ 파일읽기

▼ 내용

var fs = require('fs'); fs.readFile('sample.txt','utf8',function(err,data){ console.log(data); }); //sample.txt 의 내용 출력

require('fs'); 는 node 모듈에 파일시스템을 가져온다는 의미이다.

fs.readFile 의 첫번쨰 인자는 읽을 파일경로 (현재실행 디렉토리 기준 path 입니다.)

두번째 인자는 문자 캐릭터 (생략시 헥사코드로 나옴 , 바이너리데이터)

세번쨰 인자로 콜백함수를 넣어줬습니다. data 가 읽은 파일의 데이터 입니다.


◎ 파일목록 가져오기

var fs = require('fs'); fs.readdir('./test',function(err,filelist){ console.log(filelist); }); //[ 'css3', 'file.js' ]

▼ 내용

fs 의 readdir 을 쓰면 파일 목록을 배열에 담아서 가져온다


◎ 파일 생성

var fs = require('fs'); fs.writeFile('파일경로/파일명','파일에들어갈내용',function(err){ if (err === null) { console.log('success'); } else { console.log('fail'); } });

▼ 내용

fs.writeFile 의 첫번째인자는 파일명 , 두번째 인자는 파일의 내용 , 세번째는 콜백함수 이다.

콜백함수엔 err을 인자로 줄수있으며 err은 에러가 낫을경우이다.


◎ 파일 이름 수정 , 파일 내용 수정

fs.rename(oldPath, newPath, callback)

▼ 내용

fs.rename(oldPath, newPath, callback)

fs.writeFile 의 첫번째인자는 파일명 , 두번째 인자는 파일의 내용 , 세번째는 콜백함수 이다.

콜백함수엔 err을 인자로 줄수있으며 err은 에러가 낫을경우이다.

예제)

fs.rename(`./data/${title_ori}`,`./data/${title}`,()=>{ //파일 이름 바꾸기 fs.writeFile('./data/'+title,'파일수정할내용','utf8',function(err){ // 파일 내용 수정 if (err ===undefined || err == null){ response.writeHead(302, {Location: `/?id=${title}`}); //요청한 주소로 리다이렉션 response.end(); } }); });

◎ 파일 삭제

fs.unlink(Path, callback)

▼ 내용

fs.unlink(Path, callback)

fs.unlink 의 첫번째인자는 파일경로+파일명, 두번째는 콜백함수 이다.

콜백함수엔 err을 인자로 줄수있으며 err은 에러가 낫을경우이다.

예제)

fs.unlink(`./data/${post.id}`,(err)=>{ console.log(post.id); response.writeHead(302, {Location: `/`}); //요청한 주소로 리다이렉션 response.end(); })

예제)

fs.rename(`./data/${title_ori}`,`./data/${title}`,()=>{ //파일 이름 바꾸기 fs.writeFile('./data/'+title,description,'utf8',function(err){ // 파일 내용 수정 if (err ===undefined || err == null){ response.writeHead(302, {Location: `/?id=${title}`}); //요청한 주소로 리다이렉션 response.end(); } }); });

◎ 동기와 비동기

▼ 내용

파일의 목록을 콘솔에 출력하고 파일의 내용을 콘솔에 출력하고 싶다.

fs.readFile(`data/${queryData.id}`,'utf8',function(err,description){ fs.readdir('./data',function(err,filelist){ console.log(filelist); }) console.log(description); })

위와 같이 작성하면 filelist 가 먼저고 그다음 파일 내용을 출력할것 같지만...

그렇지 않다 실상 출력을 해보면 파일 내용 먼저 출력되고 filelist가 출력이된다.

그 이유는 node js의 함수는 기본적으로 모두 비동기로 처리되기 때문이다.

그래서 위의 readFile 과 readdir 의 메소드들은 모두 비동기로 처리가됬다.

이걸 동기로 바꾸려면

fs.readFile(`data/${queryData.id}`,'utf8',function(err,description){ var filelist = fs.readdirSync('./data'); console.log(filelist); console.log(description); })

이렇게 바꿔야 한다.

node js 의 fs 함수같은경우 비동기 함수와 동기 함수를 모두 제공해준다

대부분 이름을 보면 동기함수 뒤에 Sync 를 붙혀서 제공된다.

단 동기함수같은경운 리턴값을 변수로 받아서 위와같이 작업을 해야한다.

자세한설명은 아래 링크를 참조

https://opentutorials.org/module/938/7373


반응형

+ Recent posts