NodeJS 产生标准输出字符串格式 [英] NodeJS spawn stdout string format

查看:75
本文介绍了NodeJS 产生标准输出字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在节点中生成一个进程并像这样跟踪命令的输出:

I'm spawning a process in node and tracking the output of the command like this:

proc.stdout.on("data", function (data) {
    console.log(data.toString());
});

效果很好,但是,输出似乎在分割线:

It works well, however, the output seems to be splitting the lines:

npm http
 304 https://registry.npmjs.org/underscore

以上只是 npm install 响应中的一行.通常这都在一行中,它还在响应之前和之后添加换行符.有没有办法让数据输出看起来像标准运行,即逐行?

The above is just one line out of the response from an npm install. Typically this is all in one line, it's also adding line breaks before and after the response. Is there a way to get the data output to look like the standard run, i.e. line-by-line?

推荐答案

Streams 被缓冲并在需要时发出 data 事件(可以这么说),而不是像文本行这样的严格边界.

Streams are buffered and emit data events whenever they please (so to speak), not on strict boundaries like lines of text.

但是您可以使用 readline 模块来解析缓冲区为您排成一行:

But you can use the readline module to parse the buffers into lines for you:

var child_process = require('child_process');
var readline      = require('readline');
var proc          = child_process.spawn(...);

readline.createInterface({
  input     : proc.stdout,
  terminal  : false
}).on('line', function(line) {
  console.log(line);
});

这篇关于NodeJS 产生标准输出字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆