这是一个创建于 2007 天前的主题,其中的信息可能已经有所发展或是发生改变。
nodejs socket 程序, 用到 crypto 做简单的签名加解密, 了解到 crypto 不是异步的
这样在 socket 事件的 callback 中,
直接调用 Cipher Decipher 的 update, final, 如果并发多了是不是特别影响性能?
如果用 stream 呢?
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
let encrypted = '';
cipher.on('readable', () => {
const data = cipher.read();
if (data)
encrypted += data.toString('hex');
});
cipher.on('end', () => {
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
});
cipher.write('some clear text data');
cipher.end();
官方文档里的这种写法看起来是异步的, 是否说这样写只是改变了 chipher 在主线程循环里执行的时机?
如果用 async 函数把 cipher 操作包裹起来呢? 但貌似不能在 cipher 上用 await 调用是吧
像这种基本的应用,怎么做才不会影响 nodejs 事件循环的效率?
另外像在 net socket 这种 callback 的架构里,没法直接用 await 调用 async 函数吧,这样是否加一层 async 函数,再在 callback 里直接调用这个 async 函数?
4 条回复 • 2019-08-22 09:48:32 +08:00
![janxin](https://cdn.v2ex.com/avatar/6ebb/69ff/8042_normal.png?m=1334151332) |
|
1
janxin 2019-08-21 16:21:06 +08:00
crypto 又不是 io 操作不是异步挺正常呀...
|
![ahsjs](https://cdn.v2ex.com/gravatar/4d50bf9d36698df1981f46f1cf8c01bf?s=48&d=retro) |
|
2
ahsjs 2019-08-21 16:30:31 +08:00
包到 promise 里?
|
![rrfeng](https://cdn.v2ex.com/avatar/0bb1/03d9/21425_normal.png?m=1366707259) |
|
3
rrfeng 2019-08-21 16:52:18 +08:00 1
异步是为了啥?空闲 CPU 给其他操作用。 crypto 属于典型的密集计算操作,CPU 不会闲下来的,所以没必要异步。
你可以将 crypto 发送给另一个进程 /线程 /协程,以达到不阻塞主进程的目的,但是这算是应用层的设计了。
|
![naquda](https://cdn.v2ex.com/gravatar/9e232f664e88a8e1a0fe586017ee5369?s=48&d=retro) |
|
4
naquda 2019-08-22 09:48:32 +08:00
|