readNDJSON

Read a file as newline-delimited JSON.

Usage

var readNDJSON = require( '@stdlib/fs/read-ndjson' );

readNDJSON( file[, options], clbk )

Asynchronously reads a file as newline-delimited JSON.

var join = require( 'path' ).join;

readNDJSON( join( __dirname, 'examples', 'fixtures', 'file.ndjson' ), clbk );

function clbk( error, data ) {
    if ( error ) {
        throw error;
    }
    console.log( data );
}

The function accepts the following options:

  • encoding: file encoding.
  • flag: file status flag.
  • reviver: JSON transformation function.

The options parameter may also be a string specifying the file encoding.

var join = require( 'path' ).join;

readNDJSON( join( __dirname, 'examples', 'fixtures', 'file.ndjson' ), 'utf8', clbk );

function clbk( error, data ) {
    if ( error ) {
        throw error;
    }
    console.log( data );
}

readNDJSON.sync( file[, options] )

Synchronously reads a file as newline-delimited JSON.

var join = require( 'path' ).join;
var instanceOf = require( '@stdlib/assert/instance-of' );

var out = readNDJSON.sync( join( __dirname, 'examples', 'fixtures', 'file.ndjson' ) );
if ( instanceOf( out, Error ) ) {
    throw out;
}
console.log( out );

The function accepts the same options as readNDJSON() above.

Notes

Examples

var join = require( 'path' ).join;
var readNDJSON = require( '@stdlib/fs/read-ndjson' );

var file = join( __dirname, 'examples', 'fixtures', 'file.ndjson' );

// Synchronously read file contents...
var data = readNDJSON.sync( file, 'utf8' );
// returns [...]

data = readNDJSON.sync( 'beepboop', {
    'encoding': 'utf8'
});
// returns <Error>

// Asynchronously read file contents...
readNDJSON( file, clbk );
readNDJSON( 'beepboop', clbk );

function clbk( error, data ) {
    if ( error ) {
        if ( error.code === 'ENOENT' ) {
            console.error( 'JSON file does not exist.' );
        } else {
            throw error;
        }
    } else {
        console.log( 'Package description: %s', data[2].description );
    }
}
Did you find this page helpful?