본문 바로가기
node.js

노드js 파일/파일경로 관리하기

by PudgeKim 2021. 5. 28.

ES6 기준으로 dirname과 filename은 아래처럼 import를 이용하면 됩니다. (물론 require로 해도 상관없습니다.)

1
2
3
4
5
6
7
8
9
import path from 'path'
import { fileURLToPath } from 'url';
 
 
const __dirname = path.resolve();
console.log(__dirname)
 
const __filename = fileURLToPath(import.meta.url)
console.log(__filename)
cs

 

__filename의 경우 .../.../.../.../main.js 이런식으로 나오게 됩니다.
만약 main.js라는 것만 출력하고 싶다면

1
2
3
4
const __filename = fileURLToPath(import.meta.url)
console.log(__filename)
 
console.log(path.basename(__filename))
cs

path.basename을 이용하면 됩니다. basename의 두번째 인자는 optional인데 만약 두번째 인자로
.js를 주게되면 main.js가 아닌 main만 출력됩니다.

그 밖의 path.dirname(__filename의 디렉토리 출력), path.extname(확장자 출력), path.parse 등이 있습니다.

 

이러한 경로를 이용해서 파일이름 등을 바꾸고 싶다면 fs 모듈을 이용하면 됩니다.

1
2
3
4
import fs from 'fs';
 
 
fs.renameSync('./test.txt', './super.txt')
cs

위 코드는 현재 경로에 있는 test.txt 파일의 이름을 super.txt로 바꾸는 코드입니다.
renameSync에서 뒤에 Sync는 동기적으로 처리하는 것을 나타냅니다. (sync보단 promise나 rename함수를 사용하는게 권장됩니다.)

rename함수를 통해 비동기로 에러에 관한 콜백함수를 전달할 수 있습니다.

 

폴더를 만들고 싶다면

1
2
3
4
const fs = require('fs').promises
 
fs.mkdir('testFolder')
.catch(console.error)
cs

fs모듈의 promises를 가져와서 mkdir 함수를 이용하면 됩니다.

 

특정 경로에 모든 폴더와 파일이름을 보고싶다면

1
2
3
4
5
6
const fs = require('fs').promises
 
 
fs.readdir('./')
.then(console.log)
.catch(console.error)
cs

위는 현재 경로에 모든 파일/폴더를 출력하는 예제입니다. 역시 fs의 promises모듈을 사용합니다.
(위처럼 require을 사용할때는 package.json에서 type: commonjs를 추가해줍니다.)

 

파일 읽기

1
2
3
4
5
6
7
8
9
const fs = require('fs').promises
 
fs.readFile('./test.txt')
.then((text) => console.log(text))
 
// Buffer 형태로 출력됨
 
fs.readFile('./test.txt''utf8')
// 위처럼 해야 의도했던 text가 출력됨
cs

파일 쓰기

1
2
fs.writeFile('./test.txt', 'hello world')
.catch(console.error)
cs

그 밖의 copyFile 등이 있습니다.

 

'node.js' 카테고리의 다른 글

노드js Buffer&Stream  (0) 2021.05.28
node.js Interval과 nextTick  (0) 2021.05.27