Last active
February 14, 2022 13:16
-
-
Save kiddpt/b753cfce64f264c1e4e5 to your computer and use it in GitHub Desktop.
Fast and easy CSV download by streaming for node-express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var csv = require('fast-csv'); | |
var mysql = require('mysql'); | |
var connection = mysql.createConnection(config.mysql); | |
var pool = mysql.createPool({ | |
connectionLimit: 10, | |
host: config.mysql.host, | |
user: config.mysql.user, | |
password: config.mysql.password, | |
database: config.mysql.database, | |
port: config.mysql.port | |
}); | |
pool.getConnection(function(err, connection) { | |
if (err) { | |
console.log('connection error', err); | |
} else { | |
var csvStream = csv | |
.createWriteStream({ | |
headers: true | |
}); | |
res.setHeader('Content-disposition', 'attachment; filename=download.csv'); | |
res.setHeader('Content-type', 'text/csv'); | |
csvStream.pipe(res); | |
var sql = connection.query({ | |
sql: query, | |
values: [] | |
}).on('result', function(row) { | |
csvStream.write(row); | |
}).on('end', function() { | |
csvStream.end(); | |
connection.release(); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also use the stream transform