【问题标题】:Listen to (own) process.stdout (in Node.js)收听(自己的)process.stdout(在 Node.js 中)
【发布时间】:2023-01-19 04:54:34
【问题描述】:

对于熟悉该主题的人来说,这可能是一个基本问题。考虑以下玩具程序:

  const fs = require('fs');
  process.stdout.on('data', (chunk) => {
    fs.writeFileSync('myfile.txt', chunk, 'utf-8'); // just an example
  });
  process.stdout.write('xyz');

如果我按原样运行这段代码,我会收到以下错误:

  errno: -4053,
  code: 'ENOTCONN',
  syscall: 'read'

我已经不明白为什么会这样。但它变得更加奇怪:

当我在它之前运行带有 console.log() 的代码时,不再抛出任何错误!但是,我为 data 事件定义的侦听器在这种情况下似乎不会执行,因为没有创建文本文件。

有人可以向我解释为什么会发生这种情况以及我可以做些什么来获得预期的结果(此处写​​入 myfile.txt)?

【问题讨论】:

    标签: node.js io stream stdout


    【解决方案1】:

    您看到的第一个错误是由于尝试连接到 stdout 以获取它的 data 引起的。你还没有向stdout写入任何东西,所以它没有被初始化,所以你无法连接到它! ENOTCONN 的意思就是:Error: Not Connected(到 stdout 套接字)。

    现在,对于第二个错误。当您运行前面带有 console.log() 的代码时,您现在已经初始化了 stdout,因此您可以连接到它并且不会抛出 ENOTCONN 错误。但是您正在等待来自 stdout 的控制台的输入。输入不是来自stdout;它来自stdin

    要解决此问题,您需要:

    1. 在连接之前初始化stdin,使用process.stdin.resume()
    2. 等待来自stdindata,而不是stdout,使用process.stdin.on(...)
    3. 当您使用process.exit(0)stdin 接收完输入后,成功退出程序。
      const fs = require('fs')
      
      process.stdin.resume()
      process.stdin.on('data', (chunk) => {
        fs.writeFileSync('mytestfile.txt', chunk, 'utf-8')
      
        // Uncomment the following line if you want to write
        // something to the console to indicate success
        // process.stdout.write("Got your input!")
      
        process.exit(0)
      })
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多