crypto.randomBytes(64, (err, buf) =>{
const salt = buf.toString('base64');
console.log('salt', salt);
console.time('암호화')
crypto.pbkdf2('fabxoe바보', salt, 501395, 64, 'sha512', (err, key)=>{
console.log('password', key.toString('base64'));
console.timeEnd('암호화');
});
});
콜백지옥을 보여주고 있는 콜백함수.
promise로 바꾸려고 해도 아무나 바꿀 수 있는게 아니다.
지원을 해줘야한다. 애초에 메서드를 만들때 내부를 Promise 생성자로 만들었어야 지원해준다.
그러나 지원하지 않는 콜백함수를 Promise를 지원하게 만드는 방법이 있다고 한다.
const randomBytesPromise = util.promisify(crypto.randomBytes);
const pbkdf2Promise = util.promisify(crypto.pbkdf2);
randomBytesPromise(64)
.then((buf) => {
const salt = buf.toString('base64');
return pbkdf2Promise('fabxoe바보',salt, 501394, 64, 'sha512');
})
.then((key)=>{
console.log('password', key.toString('base64'));
})
.then((err)=>{
console.timeEnd('암호화');
});
바로 promisify함수를 이용하면 지원할 수 있게 만들어 준다. promise로 만들 수 있게 되었다.
(async () => {
const buf = await randomBytesPromise(64);
const salt = buf.toString('base64');
const key = await pbkdf2Promise('fabxoe바보',salt, 501394, 64, 'sha512');
})
우리가 알기로서는 Promise를 지원한다면 당연히 async로도 만들수 있었다. 이렇게 async로도 만들 수 있다!
'Node.js' 카테고리의 다른 글
static 미들웨어함수 (0) | 2019.10.02 |
---|---|
Node.js 개발환경 (0) | 2019.10.01 |
crypto모듈을 이용한 암호화 (0) | 2019.09.30 |
ES8(2017)에서의 변화 (0) | 2019.09.30 |
ES6(2015)에서의 변화 3 (0) | 2019.09.30 |
댓글