I am trying to create a CSV class that can be used inside other scripts in my application. When the CSV class is instantiated, it creates a writable stream to a file specified by the user. The write and destroy methods seem to work, but I can't figure out how to get the 'writeEnd' member on the class to execute once the data has finished writing to the file.
The 'writeEnd' member variable is a function that should be overridden by the user. For example, here is a file where I am testing out the classes functionality, and overriding 'writeEnd' to be a function of my own choosing.
P.S. Please see the question in bold at the bottom!
const CSV = require('./shared/classes/csv');
const csv = new CSV(__dirname);
csv.writeEnd = () => {
console.log('Finished!');
};
for (let i = 0; i < 1000000; i++) {
csv.write('Hello World.');
}
I was hoping for 'Finished!' to be logged to the console, but the function does not fire at all. I hope I am doing something wrong that someone can catch pretty easily.
For your reference, here is the class file untouched:
const { createWriteStream } = require('fs');
const { Readable } = require('stream');
/**
* @class CSV
*/
module.exports = class CSV {
constructor(path) {
this.readStream = new Readable({ read() {} });
this.writeStream = createWriteStream(`${path}/csv/data.csv`);
this.readStream.pipe(this.writeStream);
this.writeEnd = () => {};
}
/**
* @method write
* @param {any} data
*/
write(data) {
this.readStream.push(`${data}\n`);
}
/**
* @method destroy
*/
destroy() {
this.readStream.destroy();
this.writeStream.destroy();
}
};
Below, is one of my failed attempts:
/**
* @class CSV
*/
module.exports = class CSV {
constructor(path) {
this.readStream = new Readable({ read() {} });
this.writeStream = createWriteStream(`${path}/csv/data.csv`);
this.readStream.pipe(this.writeStream);
// I'm wondering if this executes immediately because no writing is taking place
// during instantiation
this.writeStream.on('finish', this.writeEnd);
this.writeEnd = () => {};
}
/**
* @method write
* @param {any} data
*/
write(data) {
this.readStream.push(`${data}\n`);
}
/**
* @method destroy
*/
destroy() {
this.readStream.destroy();
this.writeStream.destroy();
}
};
I am wondering if I need to actually listen for the very first time the readStream gets data pushed to it, then set the 'finish' callback?