Node.js로 개발할 때 자주 사용하는 코드를 정리했다.
Crypto
Crypto는 OpenSSL 해시, HMAC, cipher, decipher, 서명, 증명 함수 등의 wrapper 세트를 포함한 암호 기능을 제공하는 모듈이다.
Node.js Crypto API
비밀번호를 디비에 암호화해서 저장할 때 사용할 수 있는 sha256 암호화 예제다.
|
const crypto = require('crypto'); // ES6 - import crypto from 'crypto'; const secret = 'abcdefg'; const hash = crypto.createHmac('sha256', secret) .update('I love cupcakes') .digest('hex'); console.log(hash); // Prints: // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e |
파일 시스템
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
// 현재 파일 경로 __filename; // D:\workspace\diagram\main.js // 현재 디렉토리 __dirname; // D:\workspace\diagram // 경로 연결 path.join(__dirname, '/test') // /home/dirname/test // 상대적인 경로로 연결. path.resolve('/foo/bar', './baz') // /foo/bar/baz // 경로에 해당하는 속성을 가져온다.(root, dir, base, ext, name) path.parse("/usr/local/test.jpg") // 경로에서 파일명만 가져오기 path.basename('/foo/bar/baz/asdf/quux.html') // Returns: 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html') // Returns: 'quux' // 디렉토리 이동. cwd 변경. process.chdir('/tmp'); // 파일이동, 이름 변경 fs.renameSync(oldPath, newPath); // 파일 삭제 fs.unlinkSync(path); |
Gulp
gulpfile.babel.js를 사용할 때 SyntaxError 발생
gulpfile에 ES6 문법을 사용할 때, 다음 에러가 뜰 수 있다. 예를들어, import 할 때.
|
SyntaxError: Unexpected reserved word |
babel-core가 없을 때 발생할 수 있다.
|
# babel 있는지 확인 npm ls babel # 없으면 설치 npm install babel-core --save-dev |
Express.js
|
// 응답 헤더 지정 res.set('Content-Type', 'image/png'); // URL 파싱 require('url').parse(req.url) // 정규식 패턴을 사용한 라우팅 (puml로 끝나는 경우) app.get(/\.puml$/, function(req, res) { } |
NPM 사용
|
# production으로 모듈 설치 NODE_ENV=production npm install --only=prod # 개발 디펜던시만 설치 npm install --only=dev |
모듈
내가 사용했던 유용한 Node.js 모듈이다. 더 많은 모듈을 npmjs에서 검색할 수 있다.