NodeJS exec使用来自进程的二进制文件

我正在尝试编写一个函数,它会使用本地openssl为我做一些RSA繁重的工作,而不是使用js RSA库。 目标是

  1. 从文件读取二进制数据
  2. 在节点进程中使用JS做一些处理,产生一个包含二进制数据的缓冲区
  3. 将缓冲区写入exec命令的stdinstream
  4. RSAencryption/解密数据并将其写入标准输出stream
  5. 获取input数据返回到JS进程中的缓冲区进行进一步处理

Node中的subprocess模块有一个exec命令,但是我看不到如何将input传送给进程并将其传回到进程中。 基本上我想执行以下types的命令,但不必依赖写入文件(没有检查openssl的确切语法)

cat the_binary_file.data | openssl -encrypt -inkey key_file.pem -certin > the_output_stream 

我可以通过编写一个临时文件来做到这一点,但是如果可能的话,我想避免它。 产生一个subprocess允许我访问stdin / out,但没有findexec的这个function。

我在这里起草的方式是否有一个干净的方式来做到这一点? 是否有一些使用openssl的替代方式,例如openssl lib的一些本地绑定,这将允许我这样做,而不依赖于命令行?

你已经提到了spawn但似乎认为你不能使用它。 可能在这里显示我的无知,但它似乎应该只是你要找的东西:通过spawn启动openssl,然后写入child.stdin并从child.stdout读取。 非常粗略的这个完全未经testing的代码:

 var util = require('util'), spawn = require('child_process').spawn; function sslencrypt(buffer_to_encrypt, callback) { var ssl = spawn('openssl', ['-encrypt', '-inkey', ',key_file.pem', '-certin']), result = new Buffer(SOME_APPROPRIATE_SIZE), resultSize = 0; ssl.stdout.on('data', function (data) { // Save up the result (or perhaps just call the callback repeatedly // with it as it comes, whatever) if (data.length + resultSize > result.length) { // Too much data, our SOME_APPROPRIATE_SIZE above wasn't big enough } else { // Append to our buffer resultSize += data.length; data.copy(result); } }); ssl.stderr.on('data', function (data) { // Handle error output }); ssl.on('exit', function (code) { // Done, trigger your callback (perhaps check `code` here) callback(result, resultSize); }); // Write the buffer ssl.stdin.write(buffer_to_encrypt); } 

你应该可以设置编码为二进制,当你打电话给exec,如..

 exec("openssl output_something_in_binary", {encoding: 'binary'}, function(err, out, err) { //do something with out - which is in the binary format }); 

如果你想用二进制写出“out”的内容,请确保将编码再次设置为二进制,如..

 fs.writeFile("out.bin", out, {encoding: 'binary'}); 

我希望这有帮助!