Skip to content

A Node.js module for reading files line by line

License

Notifications You must be signed in to change notification settings

BigLiao/fs-line

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fs-line

A Node.js module for reading files line by line.

Features

  • Read file line by line, synchronously or asynchronously.
  • Using Stream, can handler big file without put it in memory.
  • Transform line string while reading.

Installation

npm install fs-line

Usage

Read and console each line:

const FsLine = require('fs-line');

const fsLine = new FsLine();
fsLine.open(FILE_PATH);
let lineCount = 0;
fsLine.on('line', (line, next) => {
    console.log('%d: %s', ++lineCount, line);
    next();
});

Or asynchronously:

const FsLine = require('fs-line');

const fsLine = new FsLine();
fsLine.open(FILE_PATH);
let lineCount = 0;
fsLine.on('line', (line, next) => {
    console.log('%d: %s', ++lineCount, line);
    setTimeout(next, 1000)
});

Remember to call next to read next line.

The next function can pass a input string as a replacement for current line:

const FsLine = require('fs-line');

const fsLine = new FsLine();
fsLine.open(FILE_PATH);
let lineCount = 0;
fsLine.on('line', (line, next) => {
    const newLine = transform(line);
    next(newLine);
});

API

Class: FsLine([options])

Create a fsline instance.

const FsLine = require('fs-line');
const fsline = new FsLine();

options: object, with following defaults:

{
    encoding: 'utf8',
    separator: '\n',
}

You can change the separator to such as '\r\n'.

Event: 'line'

Emit when a line is read, first argument is the line string, and the second argument is next function call to read next line.

fsline.on('line', function(line, next) {
    // do some thing...
    next();
})

If a argument is passed to next function, then this line will be changed to the input argument:

fsline.on('line', function(line, next) {
    // do some thing...
    next('===>' + line);
})

Event: 'end'

All data is read.

Method: fsline.open(file)

Open a file, and begin to read.

file <sting>: the file path

Method: fsline.close()

Close the file, end the read stream.

About

A Node.js module for reading files line by line

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published