npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

csv-builder

v1.0.1

Published

Easily encode complex JSON objects to CSV with CsvBuilder's schema-like API

Downloads

7,689

Readme

Csvbuilder

travis

Easily encode complex JSON objects to CSV with CsvBuilder's schema-like API.

Table Of Contents

Usage


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)

Installation

$ npm i -s csv-builder
# or
$ yarn add csv-builder

New Features

  • More cohesive API
  • Expanded API to support non-stream outputs, i.e. building a CSV string row-by-row with the getHeaders() and getRow(object) methods respectively.
  • Better CSV encoding (proper quoting by default)

API

CsvBuilder([options])
  • headers String|Array Space separated headers, or array of headers (required)
  • delimiter String The column delimiter. Default ','
  • terminator String The row terminator. Default '\n'
  • quoted Boolean Quote columns? Default true
  • alias Object An object in the format of { "csv header": "object prop" }, object prop will be aliased to csv header. Default {}

Methods

CsvBuilder#createReadStream(payload): Stream.Readable

Creates a readable stream and consumes the payload.

  • payload Array<Object> Incoming data.
CsvBuilder#createTransformStream(): Stream.Transform

Creates a transform stream. The stream expects either Objects or JSON.

CsvBuilder#headers(headers): this
  • headers String|Array Space separated headers, or array of headers
CsvBuilder#alias(header, prop): this

Set single or multiple contraints. If header is an object, it will extend any existing constraints, not replace.

  • header String|Object Either object {"header": "property"} Or a string "Header"
  • prop String|undefined Property to correspond to header, omit if using object.
CsvBuilder#virtual(prop, fn): this

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.

  • prop String Virtual property name
  • fn (item: any) => any Where item is an element from the incoming data, and the return value is the corresponding value for the virtualized property.
CsvBuilder#getHeaders(): String

The headers in CSV format

CsvBuilder#getRow(item): String

Returns the CSV formated row for a given item.

  • item Object A n item matching the "schema".

Migration to 1.0.0

  • constraints attribute in options (for constructor) is deprecated, use alias instead.
  • set(prop, value) method is deprecated, use alias(prop, value) instead.