V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
naquda
V2EX  ›  Node.js

nodejs crypto 不是异步么

  •  
  •   naquda · 2019-08-21 14:47:06 +08:00 · 5025 次点击
    这是一个创建于 1707 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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
        1
    janxin  
       2019-08-21 16:21:06 +08:00
    crypto 又不是 io 操作不是异步挺正常呀...
    ahsjs
        2
    ahsjs  
       2019-08-21 16:30:31 +08:00
    包到 promise 里?
    rrfeng
        3
    rrfeng  
       2019-08-21 16:52:18 +08:00   ❤️ 1
    异步是为了啥?空闲 CPU 给其他操作用。
    crypto 属于典型的密集计算操作,CPU 不会闲下来的,所以没必要异步。

    你可以将 crypto 发送给另一个进程 /线程 /协程,以达到不阻塞主进程的目的,但是这算是应用层的设计了。
    naquda
        4
    naquda  
    OP
       2019-08-22 09:48:32 +08:00
    @rrfeng 有理,也就是想不阻塞事件循环
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1220 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:18 · PVG 07:18 · LAX 16:18 · JFK 19:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.