Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: node Writable stream wrapper around table.createStream #86

Open
CodeMan99 opened this issue Dec 23, 2018 · 0 comments
Open

Comments

@CodeMan99
Copy link

CodeMan99 commented Dec 23, 2018

Opening as issue because I am not sure where the code should land.

Shipping a writable wrapper is easy as defining _write and _final methods.

const {Writable} = require('stream'); // or "readable-stream" if you prefer

function WriteTableStream(options) {
	if (!(this instanceof WriteTableStream)) {
		return new WriteTableStream(options);
	}

	options = Object.assign({objectMode: true}, options);
	Writable.call(this, options);
	this._tableStream = createStream(options);
}

// or require('util').inherits if you prefer. Honestly, I hate that Object.setPrototypeOf is used there
WriteTableStream.super_ = Writable;
WriteTableStream.prototype = Object.create(Writable.prototype, {
	constructor: {
		configurable: true,
		enumerable: false,
		value: WriteTableStream,
		writable: true
	}
});

WriteTableStream.prototype._write = function(chunk, encoding, next) {
	let err = null;

	try {
		this._tableStream.write(chunk);
	} catch (e) {
		err = e;
	}

	next(err);
};

WriteTableStream.prototype._final = function(done) {
	process.stdout.write('\n', done);
};

This allows users to create a pipeline that transforms their data into row arrays. For example maybe read a csv file in a stream.

fs.createReadStream('data.csv')
    // https://github.com/mcollina/split2
    .pipe(split(line => line.split(','), {trailing: false}))
    .pipe(new WriteTableStream(options));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants