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
24 changes: 19 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ var gen = require('generate-object-property')

var CsvWriteStream = function(opts) {
if (!opts) opts = {}
stream.Transform.call(this, {objectMode:true, highWaterMark:16})
stream.Transform.call(this, { objectMode:true, highWaterMark:16 })

this.sendHeaders = opts.sendHeaders !== false
this.headers = opts.headers || null
Expand All @@ -25,9 +25,15 @@ CsvWriteStream.prototype._compile = function(headers) {
var str = 'function toRow(obj) {\n'

if (!headers.length) str += '""'
var rawheaders = this.headers;

headers = headers.map(function(prop, i) {
str += 'var a'+i+' = '+prop+' == null ? "" : '+prop+'\n'
if (typeof rawheaders[i] === 'object') {
var def = rawheaders[i].default || ''
str += 'var a'+i+' = '+prop+' == null ? "'+def+'" : '+prop+'\n'
} else {
str += 'var a'+i+' = '+prop+' == null ? "" : '+prop+'\n'
}
return 'a'+i
})

Expand Down Expand Up @@ -58,14 +64,22 @@ CsvWriteStream.prototype._transform = function(row, enc, cb) {
var heads = []

for (var i = 0; i < this.headers.length; i++) {
arrProps.push('obj['+i+']')
objProps.push(gen('obj', this.headers[i]))

if (typeof this.headers[i] === 'object') {
arrProps.push('obj['+i+']')
objProps.push(gen('obj', this.headers[i].field))
heads.push(this.headers[i].title || this.headers[i].field)
} else {
arrProps.push('obj['+i+']')
objProps.push(gen('obj', this.headers[i]))
heads.push(this.headers[i])
}
}

this._objRow = this._compile(objProps)
this._arrRow = this._compile(arrProps)

if (this.sendHeaders) this.push(this._arrRow(this.headers))
if (this.sendHeaders) this.push(this._arrRow(heads))
}

if (isArray) {
Expand Down
219 changes: 219 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ var writer = csvWriter()

`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.

`headers` can also be an array of objects containing a header title, field and default. The `title` will replace the field in header. The `field` defines the object key. The `default` set the default value if a key is not found in a given row.

example of auto headers:

```javascript
Expand Down Expand Up @@ -65,6 +67,25 @@ writer.end()
// produces: world,bar,taco\n
```

example of with headers objects (title, field and defaults):
note: header objects does not work in the cli.

```javascript
var headers = [
{ title: 'SSN', field: 'ssn_value', default: 'NA'},
{ title: 'First Name', field: 'fName', default: ''},
{ title: 'Last Name', field: 'lName', default: ''}
]
var writer = csvWriter({ headers: headers })
writer.pipe(fs.createWriteStream('out.csv'))
writer.write({ fName: 'Joe', lName: 'Dirt', ssn_value: '111-22-3333'})
writer.end()

// produces:
// SSN,First Name,Last Name\n
// 000-11-0000,Joe,Dirt\n
```

see the test suite for more examples

## run the test suite
Expand Down
55 changes: 55 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,58 @@ test('lots of cols', function (t) {
writer.write(obj)
writer.end()
})

test('header objects', function(t) {

var headers = [
{ title: 'My Foo', field: 'foo' },
{ title: 'My Bar', field: 'bar' }
]

var writer = csv({ headers: headers })

writer.pipe(concat(function(data) {
t.equal('My Foo,My Bar\nfoo,bar\n', data.toString())
t.end()
}))

writer.write({ foo: 'foo', bar: 'bar' })
writer.end()
})

test('header objects with basic array', function(t) {

var headers = [
{ title: 'My Foo', field: 'foo' },
{ title: 'My Bar', field: 'bar' }
]

var writer = csv({ headers: headers })

writer.pipe(concat(function(data) {
t.equal('My Foo,My Bar\nfoo,bar\n', data.toString())
t.end()
}))

writer.write(["foo", "bar"])
writer.end()
})

test('header objects with default with basic array', function(t) {

var headers = [
{ title: 'My Foo', field: 'foo' },
{ title: 'My Bar', field: 'bar' },
{ title: 'My Bad', field: 'bad', default: '--' }
]

var writer = csv({ headers: headers })

writer.pipe(concat(function(data) {
t.equal('My Foo,My Bar,My Bad\nfoo,bar,--\n', data.toString())
t.end()
}))

writer.write(["foo", "bar"])
writer.end()
})