Node custom readable stream

Published on:

This guy creates a CSV file of fake IDs and ACCOUNTIDs. It's a simple example of a custom readable stream in node.

Run it like this.

./generate-uuids.js 100000 > 100k.csv

generate-uuids.js

#!/usr/bin/env node

'use strict';

var Readable = require('stream').Readable;
var uuid = require('node-uuid');
var util = require('util');

// test class to generate a bunch of unique ids to load into map
// 100k seems no problem. 1 million you run out of memory.
// ./generate-uuids.js 100000 > csv/million.csv

function UUIDsReadStream(max) {
  max = !!max ? parseInt(max, 10) : 10;
  max = isNaN(max) ? 10 : max;
  Readable.call(this);
  this.index = 0;
  this.max = max;
}

util.inherits(UUIDsReadStream, Readable);

UUIDsReadStream.prototype._read = function() {
  if (this.index++ > this.max) {
    this.push(null);
  } else if (this.index === 1) {
    this.push('ID, ACCOUNTID\n');
  } else {
    this.push(`${uuid.v4()}, ${uuid.v4()}\n`);
  }
};

var uuidStr = new UUIDsReadStream(process.argv[2])
  .on('end', () => {
    // console.log('end');
  }).on('error', function(err) {
    console.log('err', err);
    process.exit(6);
  });

uuidStr.pipe(process.stdout);