简体   繁体   中英

Output breaking in child Process by nodejs

I connected wavecom GSM modem on ubantu. I use node.js language to communicate with GSM modem. I send command to modem by 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.

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 :

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 .

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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