NodeJs Stream生成进程并使用管道返回

时间:2018-10-11 11:13:14

标签: javascript node.js stream pipe spawn

我有两个文件,from.jsto.js。我尝试从to.js流到from.js,同时在to.js中列出from.js的输出,以便监视to.js的输出。

在我看来,这是一件微不足道的案子,显然我遗漏了一些东西……虽然找不到。

from.js

const {Readable} = require('stream'),
    {spawn} = require('child_process')
;
const log = (v) => console.log(v)
const to = spawn('node', ['./to.js']);

to.on('data', log);
to.on('error', log);

const from = new Readable({
    read() {
        this.push(Math.random().toString() + '\n');
    }
});

from
    .pipe(to.stdin)
;

to.js

process.stdin
    .pipe(process.stdout)
;

我得到Error: This socket is closed。谁能解释为什么这行不通。

{ Error: spawn node ENOENT
    at exports._errnoException (util.js:1020:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:197:32)
    at onErrorNT (internal/child_process.js:376:16)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    at Module.runMain (module.js:606:11)
    at run (bootstrap_node.js:383:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:496:3
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn node',
  path: 'node',
  spawnargs: [ './to.js' ] }
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: This socket is closed
    at Socket._writeGeneric (net.js:679:19)
    at Socket._write (net.js:730:8)
    at doWrite (_stream_writable.js:333:12)
    at writeOrBuffer (_stream_writable.js:319:5)
    at Socket.Writable.write (_stream_writable.js:245:11)
    at Socket.write (net.js:657:40)
    at Readable.ondata (_stream_readable.js:555:20)
    at emitOne (events.js:96:13)
    at Readable.emit (events.js:188:7)
    at Readable.read (_stream_readable.js:381:10)

0 个答案:

没有答案