Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to read from a child_process line by line in Node.js?

How to read from a child_process line by line in Node.js?

Problem

I am trying to make a Node.js script to analyse disk usage. For this, I shell out to du, but I am having trouble figuring out how to read the output from the child process line by line. Here's what I've tried so far:

var spawn = require("child_process").spawn,
    rl = require('readline'),
    du = spawn('du', ['/home']);
    linereader = rl.createInterface(du.stdout, du.stdin);

// Read line by line.
//du.stdout.on('data', function (data) {
linereader.on('line', function (data) {
  console.log(data);
});

du.stdout.on('data' just reads chunks of data, and while readline should supposedly split its input by line, it doesn't, instead I get the exact same data (du.stdout returns a buffer, but calling .toString() on it gives me the same data I got with linereader).

Problem courtesy of: mikl

Solution

Readline is broken in the current stable version (0.6.14) of Node.js. We had the same problem here:

https://stackoverflow.com/a/10012306/362536

However, there is a real quick snippet of code from TooTallNate that fixes this problem for you: https://gist.github.com/1785026

There is a pull request to fix this in later versions, and it should be in the 0.7.8 release.

Solution courtesy of: Brad

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to read from a child_process line by line in Node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×