Easily encode complex JSON objects to CSV with CsvBuilder's schema-like API.
const CsvBuilder = require('csv-builder')
const data = [
{
name: 'Foo Bar',
meta: {
active: true,
roles: [
'user',
'admin'
]
}
}
]
const builder = new CsvBuilder({
headers: ['Firstname', 'Lastname', 'Role 1', 'Role 2', 'Active'],
alias: {
'Role 1': 'meta.roles[0]',
'Role 2': 'meta.roles[1]',
'Active': 'meta.active'
}
})
.virtual('Firstname', user => user.name.split(' ')[0])
.virtual('Lastname', user => user.name.split(' ')[1])
/* Each of the following produces the following CSV contents:
"Firstname","Lastname","Role 1","Role 2","Active"
"Foo","Bar","user","admin","true"
*/
// (1) Create from a Stream of objects (like a database)
getObjectStream()
.pipe(builder.createTransformStream())
.pipe(fs.createWriteStream('output.csv'))
// (2) Create from an existing payload (`data` is an array of objects)
builder.createReadStream(data)
.pipe(fs.createWriteStream('output.csv'))
// (3) Roll your own
let csv = ''
csv += builder.getHeaders()
data.forEach(item => {
csv += builder.getRow(item)
})
fs.writeFileSync('output.csv', csv)$ npm i -s csv-builder
# or
$ yarn add csv-builder- More cohesive API
- Expanded API to support non-stream outputs, i.e. building a CSV string row-by-row with the
getHeaders()andgetRow(object)methods respectively. - Better CSV encoding (proper quoting by default)
headersString|Array Space separated headers, or array of headers (required)delimiterString The column delimiter. Default','terminatorString The row terminator. Default'\n'quotedBoolean Quote columns? DefaulttruealiasObject An object in the format of { "csv header": "object prop" },object propwill be aliased tocsv header. Default{}
Creates a readable stream and consumes the payload.
payloadArray<Object> Incoming data.
Creates a transform stream. The stream expects either Objects or JSON.
headersString|Array Space separated headers, or array of headers
Set single or multiple contraints. If header is an object, it will extend any existing constraints, not replace.
headerString|Object Either object {"header": "property"} Or a string "Header"propString|undefined Property to correspond to header, omit if using object.
Create a virtual property. Virtual properties are treated the same as normal properties. If there is no corresponding header or alias, the virtual will not be present in resulting CSV.
propString Virtual property namefn(item: any) => any Whereitemis an element from the incoming data, and the return value is the corresponding value for the virtualized property.
The headers in CSV format
Returns the CSV formated row for a given item.
itemObject A n item matching the "schema".
constraintsattribute in options (for constructor) is deprecated, usealiasinstead.set(prop, value)method is deprecated, usealias(prop, value)instead.