【问题标题】:why can i not convert this stream from process.stdout to a string为什么我不能将此流从 process.stdout 转换为字符串
【发布时间】:2019-12-05 12:22:00
【问题描述】:

所以我创建了这个服务器:

    const { createServer} = require('http');
createServer(
    (request, response) => {
        response.writeHead(200, { "Content-Type": "text/plain" });

        request.on("data", chunk => {
            response.write(chunk.toString());
        });
        request.on("end", () => {
            response.end();
        });
    }
).listen(8000);

还有这个客户:

    const {request} = require('http');
request({
    hostname:'localhost',
    port: 8000,
    method:'POST',

},response=>{
    response.on("data", chunk => process.stdout(chunk.toString()));

}).end("Hello Server");

最初我遇到getaddrinfo ENOENT 错误,但是当我连接 wifi 时它停止了,现在我收到此错误:

 response.on("data", chunk => process.stdout(chunk.toString()));
                                         ^

TypeError: process.stdout is not a function`

任何帮助的人

【问题讨论】:

  • 这听起来很烦人,但process.stdout 实际上不是一个函数。

标签: javascript node.js stream


【解决方案1】:

请试试这个

var readline = require('readline');
readline.cursorTo(process.stdout, 0);
process.stdout.write(`waiting ... ${p}%`);

【讨论】:

    【解决方案2】:

    process.stdout 是一个Stream。要写入特定流,您应该使用其write() 方法(只要它是可写流)。流对象本身不是一个函数,因此不能像一个函数那样调用。

    response.on( 'data', chunk => process.stdout.write( chunk.toString() ) );
    

    如果您真的想传递所有内容(如您当前的示例所示),您还可以使用 pipe() 方法将(可读)流的所有输出复制到(可写)流:

    response.pipe( process.stdout );
    

    【讨论】:

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