From ebb3ea727168b21bb6ec17eaeb92a5dee567959d Mon Sep 17 00:00:00 2001 From: Nil Date: Wed, 4 Jan 2017 11:44:33 +0100 Subject: [PATCH] Force double quotes enclosing using the 'enclose' option --- index.js | 8 +++++++- readme.md | 5 ++++- test.js | 12 ++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index e550bd4..7eeac71 100644 --- a/index.js +++ b/index.js @@ -10,6 +10,7 @@ var CsvWriteStream = function(opts) { this.headers = opts.headers || null this.separator = opts.separator || opts.seperator || ',' this.newline = opts.newline || '\n' + this.enclose = opts.enclose || false this._objRow = null this._arrRow = null @@ -22,6 +23,7 @@ util.inherits(CsvWriteStream, stream.Transform) CsvWriteStream.prototype._compile = function(headers) { var newline = this.newline var sep = this.separator + var enclose = this.enclose var str = 'function toRow(obj) {\n' if (!headers.length) str += '""' @@ -35,7 +37,11 @@ CsvWriteStream.prototype._compile = function(headers) { var part = headers.length < 500 ? headers : headers.slice(i, i + 500) str += i ? 'result += "'+sep+'" + ' : 'var result = ' part.forEach(function(prop, j) { - str += (j ? '+"'+sep+'"+' : '') + '(/['+sep+'\\r\\n"]/.test('+prop+') ? esc('+prop+'+"") : '+prop+')' + if (!enclose) { + str += (j ? '+"'+sep+'"+' : '') + '(/['+sep+'\\r\\n"]/.test('+prop+') ? esc('+prop+'+"") : '+prop+')' + } else { + str += (j ? '+"'+sep+'"+' : '') + 'esc('+prop+'+"")' + } }) str += '\n' } diff --git a/readme.md b/readme.md index a5d0bb5..dae1fd9 100644 --- a/readme.md +++ b/readme.md @@ -26,12 +26,15 @@ var writer = csvWriter() separator: ',', newline: '\n', headers: undefined, - sendHeaders: true + sendHeaders: true, + enclose: false, } ``` `headers` can be an array of strings to use as the header row. if you don't specify a header row the keys of the first row written to the stream will be used as the header row IF the first row is an object (see the test suite for more details). if the `sendHeaders` option is set to false, the headers will be used for ordering the data but will never be written to the stream. +`enclose` is a boolean. If true, then it will force enclosing with double quotes all the fields. If false, it will use enclosing with double quotes only if it is necessary. + example of auto headers: ```javascript diff --git a/test.js b/test.js index 7fec402..05e6fb3 100644 --- a/test.js +++ b/test.js @@ -86,6 +86,18 @@ test('encode from object w/ auto headers', function(t) { writer.end() }) +test('enclose values', function(t) { + var writer = csv({enclose: true}) + + writer.pipe(concat(function(data) { + t.equal('"hello","foo","baz"\n"world","bar","ta""co"\n', data.toString()) + t.end() + })) + + writer.write({hello: "world", foo: "bar", baz: 'ta"co'}) + writer.end() +}) + test('no headers specified', function(t) { var writer = csv()