There is another solution now with the introduction of pipeline
in Node v10 (view documentation).
The pipeline method does several things:
- Allows you to pipe through as many streams as you like.
- Provides a callback once completed.
- Importantly, it provides automatic clean up. Which is a benefit over the standard
pipe
method.
const fs = require('fs')
const mysql = require('mysql')
const {pipeline} = require('stream')
const stringify = require('csv-stringify')
const stringifier = stringify()
const output = fs.createWriteStream('query.csv')
const connection = mysql.createConnection(...)
const input = connection.query('SELECT * FROM table').stream()
pipeline(input, stringifier, process.stdout, err => {
if (err) {
console.log(err)
} else {
console.log('Output complete')
}
}