HTML5 Zone is brought to you in partnership with:

Dr. Axel Rauschmayer is a freelance software engineer, blogger and educator, located in Munich, Germany. Axel is a DZone MVB and is not an employee of DZone and has posted 246 posts at DZone. You can read more from them at their website. View Full User Profile

Read a Text Stream Line by Line with lazylines for Node.js

02.29.2012
| 2478 views |
  • submit to reddit

The new Node.js module “lazylines” allows you to read a text stream, one line at a time, lazily.

 

Examples

The following code reads input from stdin and prepends a number to each line.

    var ll = require("lazylines.js");

    process.stdin.resume();
    var inp = new ll.LineReadStream(process.stdin);
    var count = 1;
    inp.on("line", function (line) {
        console.log(count+": "+ll.chomp(line));
        count++;
    });

There are more examples in the demo/ directory. lazylines is very handy for shell programming. For example, you can implement a script that lets you do the following. 

    # List jpg files, oldest first (-t -r), then wrap
    ls -1 -t -r *.jpg | addlinecounts.js 'mv "{line}" {padi}.jpg' | bash

The above executes commands such as 

    mv "new.jpg" 001.jpg
    mv "newer.jpg" 002.jpg
    mv "newest.jpg" 003.jpg

Installation

    npm install lazylines

Related post

 

Published at DZone with permission of Axel Rauschmayer, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)