Parse output of spawned node.js child process line by line

后端 未结 6 1864
旧巷少年郎
旧巷少年郎 2020-12-07 21:05

I have a PhantomJS/CasperJS script which I\'m running from within a node.js script using process.spawn(). Since CasperJS doesn\'t support require()

6条回答
  •  -上瘾入骨i
    2020-12-07 21:42

    Adding to maerics' answer, which does not deal properly with cases where only part of a line is fed in a data dump (theirs will give you the first part and the second part of the line individually, as two separate lines.)

    var _breakOffFirstLine = /\r?\n/
    function filterStdoutDataDumpsToTextLines(callback){ //returns a function that takes chunks of stdin data, aggregates it, and passes lines one by one through to callback, all as soon as it gets them.
        var acc = ''
        return function(data){
            var splitted = data.toString().split(_breakOffFirstLine)
            var inTactLines = splitted.slice(0, splitted.length-1)
            var inTactLines[0] = acc+inTactLines[0] //if there was a partial, unended line in the previous dump, it is completed by the first section.
            acc = splitted[splitted.length-1] //if there is a partial, unended line in this dump, store it to be completed by the next (we assume there will be a terminating newline at some point. This is, generally, a safe assumption.)
            for(var i=0; i

    usage:

    process.stdout.on('data', filterStdoutDataDumpsToTextLines(function(line){
        //each time this inner function is called, you will be getting a single, complete line of the stdout ^^
    }) )
    

提交回复
热议问题