Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 += '""'
Expand All @@ -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'
}
Expand Down
5 changes: 4 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down