简体   繁体   English

子进程中的输出中断由nodejs

[英]Output breaking in child Process by nodejs

I connected wavecom GSM modem on ubantu. 我在ubantu上连接了wavecom GSM调制解调器 I use node.js language to communicate with GSM modem. 我使用node.js语言与GSM调制解调器进行通信。 I send command to modem by Child Process . 我通过Child Process向调制解调器发送命令。 Here example 这里的例子

var spawn         = require("child_process").spawn,
    exec          = require('child_process').exec;

 // Write dev_ttyUSB15.tmp file
 var child = exec('cat < /dev/ttyUSB15 > /tmp/dev_ttyUSB15.tmp');

 // Read dev_ttyUSB15.tmp file
 var m1 = spawn('tail',['-f','/tmp/dev_ttyUSB15.tmp']);

 // on data event is emitted when dev_ttyUSB15.tmp file has some data 
 m1.stdout.on('data', function (data) {
     console.log("Data : "+data); // this is executed as output
 });

Now When I fire some command on port /dev/ttyUSB15 I do not get output properly. 现在当我在端口/ dev / ttyUSB15上发出一些命令时,我没有正确输出。

Eg 例如

Suppose my output should be 假设我的输出应该是

Data : abcd1234

but instead of it I got 但我得到了而不是它

Data : abc
Data : d1234

In short My output is breaked. 简而言之,我的输出被打破了。 I can not extrapolate from where my output exactly break. 我不能从我的输出完全断开的地方推断出来。 It's random. 这是随机的。 Can anyone give me any idea? 任何人都可以给我任何想法吗?

Thanks in advance. 提前致谢。

It's hard to say without knowing what protocol you are speaking with the modem, but if it's eg \\n delimited, you will have to buffer the data and split on \\n : 很难说不知道你用调制解调器说什么协议,但如果它是例如\\n分隔,你将不得不缓冲数据并拆分\\n

var buffer = '';
m1.stdout.on('data', function(data) {
    var received = (buffer + data).split('\n');
    buffer = received.pop().trim();
    console.log(received.join(''));
});

As all streams in node.js, the reading of data consists of 2 separate events: data and end . 作为node.js中的所有流,数据读取由2个单独的事件组成: 数据结束

data event is fired when some data is readable in the stream (in your case, twice). 当某些数据在流中可读时(在您的情况下,两次),会触发数据事件。

end event is fired when no more data events will be fired. 当不再触发数据事件时触发结束事件。

var blob = "";
m1.stdout.on('data', function (data) {
 blob += data;
});

m1.stdout.on('end', function () {
 console.log("Data : " + blob); // here you have all the data within one variable
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM