Split2

In notebook:
FrontEndMasters Networking and Streams
Created at:
2017-09-30
Updated:
2017-09-30
Tags:
backend Node JS JavaScript

split2

split input on newlines (or any other kind of delimiter)

This program counts the number of lines of input, like wc -l:

You need to buffer input lines. This will assure that each buffer will be a single line.

var split = require('split2')
var through = require('through2')

var count = 0
process.stdin.pipe(split())
  .pipe(through(write, end))

function write (buf, enc, next) {
  count++
  next()
}
function end () {
  console.log(count)
}

An example that counts the newlines:

  //	****		line-count.js		****

var split = require('split2')
var to = require('to2')
var lineCount = 0 // holds the number of lines...

process.stdin
  .pipe(split())
  // so here every chunk should be a separate line now ↴
  .pipe(to(write,end))
  
function write (buf, enc, next) {
  lineCount++
  // don't forget next() !!
  next()
}
function end (next) {
  console.log(lineCount)
  next()
}

This does the same as the command line progam wc : $ wc -l < somefile.txt With node: $ node line-count.js < somefile.txt


split2

A note about split2:

In each line, the trailing '\n' is removed.


split2

You can give split() a custom string or regex to split on:

This program splits on all whitespace:

var split = require('split2')
process.stdin.pipe(split(/\s+/))
  .pipe(through(function (buf, enc, next) {
    console.log('word=' + buf.toString())
    next()
  }))