diff --git a/Readme.md b/Readme.md index bf9ed7d..b9224ae 100644 --- a/Readme.md +++ b/Readme.md @@ -62,6 +62,14 @@ app.get('/headers', function(req, res) { ], true) }) +// Add custom name +app.get('/filename', function(req, res) { + res.csv([ + {"a": 1, "b": 2, "c": 3}, + {"a": 4, "b": 5, "c": 6} + ], true, undefined, undefined, 'custom-file-name.csv') +}) + // Add response headers and status code (will throw a 500 error code) app.get('/all-params', function(req, res) { res.csv([ @@ -69,7 +77,7 @@ app.get('/all-params', function(req, res) { {"a": 4, "b": 5, "c": 6} ], true, { "Access-Control-Allow-Origin": "*" - }, 500) + }, 500, 'custom-name.csv') }) app.listen(3000) diff --git a/lib/csv-express.js b/lib/csv-express.js index 0e0e3e5..71711ad 100644 --- a/lib/csv-express.js +++ b/lib/csv-express.js @@ -59,13 +59,16 @@ function escape(field) { {status} - Optional status code */ -res.csv = function(data, csvHeaders, headers, status) { +res.csv = function(data, csvHeaders, headers, status, fileName) { var body = ''; var headerRow = []; var statusCodeSet = true this.charset = this.charset || 'utf-8'; this.header('Content-Type', 'text/csv'); + if (fileName) { + this.header('Content-disposition', `attachment; filename=${fileName}`) + } // Set custom headers if (headers && headers instanceof Object) {