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-writer-portable

v1.6.9

Published

Convert objects/arrays into a CSV string or write them into a CSV file (portable version)

Downloads

4

Readme

CSV Writer Portable

CI/CD Pipeline

Introduction

This repository serves as an enhanced version of an existing project, ryu1kn/csv-writer.

Rationale

The original project appeared to be unmaintained, leaving issues such as TypeScript compilation errors unresolved.


Features

This library enables the conversion of JavaScript objects and arrays to CSV strings or writes them directly to a file. The generated CSV complies with RFC 4180.

Prerequisites

  • Node.js (Version 16 or higher)

Webpack

Creating browser-compatible JavaScript files is now possible, thanks to the included Webpack configurations.

Here's what you can do with the available NPM scripts:

  • bundle:dev: It bundles the code and includes source maps.
  • bundle:prod: This is for production.
  • compile: Compiles TypeScript based on tsconfig.json.
  • compile-and-bundle: Compile and bundle sources in one go.
  • serve: Starts a basic HTTP server to show files from the ./public directory at http://localhost:8080.

How to Test

  1. To bundle and serve the application, run the following commands in sequence:

    npm run bundle:dev
    npm run serve

    Then, navigate to http://localhost:8080.

    csv-writer-in-browser

  2. To compile TypeScript and bundle in one go:

    npm run compile-and-bundle
    npm run serve

Quick Start

Writing Records as Array of Objects to a File

The following code snippet demonstrates how to write records, defined as an array of objects, to a file.

const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
    path: 'path/to/file.csv',
    header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
    ]
});

const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'}
];

csvWriter.writeRecords(records) // returns a promise
    .then(() => {
        console.log('...Done');
    });

The generated CSV file will contain the following:

NAME,LANGUAGE
Bob,"French, English"
Mary,English

Multiple Writes to the Same File

To append more records, simply call writeRecords again after the promise from the previous call is fulfilled.

// Usage in an async function
await csvWriter.writeRecords(records1);
await csvWriter.writeRecords(records2);

Writing Large Data Sets

For large data sets, you may want to create a Node.js transform stream and use CsvStringifier. This enables you to pipe the stream to a file write stream.

Skipping Header Line

To omit the header line, provide only the field IDs without titles.

const csvWriter = createCsvWriter({
    path: 'path/to/file.csv',
    header: ['name', 'lang']
});

If each record is defined as an array, use createArrayCsvWriter to get an csvWriter instance.

const createCsvWriter = require('csv-writer').createArrayCsvWriter;
const csvWriter = createCsvWriter({
    header: ['NAME', 'LANGUAGE'],
    path: 'path/to/file.csv'
});

const records = [
    ['Bob',  'French, English'],
    ['Mary', 'English']
];

csvWriter.writeRecords(records) // returns a promise
    .then(() => {
        console.log('...Done');
    });

This will produce a file path/to/file.csv with following contents:

NAME,LANGUAGE
Bob,"French, English"
Mary,English

If you just want to get a CSV string but don't want to write into a file, you can use createObjectCsvStringifier (or createArrayCsvStringifier) to get an csvStringifier.

const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
const csvStringifier = createCsvStringifier({
    header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
    ]
});

const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'}
];
console.log(csvStringifier.getHeaderString());
// => 'NAME,LANGUAGE\n'

console.log(csvStringifier.stringifyRecords(records));
// => 'Bob,"French, English"\nMary,English\n'

API Documentation

The following tables describe the methods exposed by the CSV Writer Portable library.

createObjectCsvWriter(params)

| Description | Link | | --- | --- | | Creates a CsvWriter instance | Source Code |

| Parameter | Type | Description | Default | | --- | --- | --- | --- | | params | Object | Configuration options | - | | └─ path | String | File path | - | | └─ header | Array<{id, title}|string> | Header specification | - | | └─ fieldDelimiter | String (Optional) | Field delimiter | , | | └─ recordDelimiter | String (Optional) | Record delimiter | \n | | └─ encoding | String (Optional) | File encoding | utf8 | | └─ append | Boolean (Optional) | Append mode | false |

Returns: CsvWriter instance


CsvWriter.writeRecords(records)

| Description | Link | | --- | --- | | Writes records to CSV | Source Code |

| Parameter | Type | Description | | --- | --- | --- | | records | Iterable | Collection of objects or arrays |

Returns: Promise


createObjectCsvStringifier(params)

| Description | Link | | --- | --- | | Creates an ObjectCsvStringifier instance | Source Code |

| Parameter | Type | Description | Default | | --- | --- | --- | --- | | params | Object | Configuration options | - | | └─ header | Array<{id, title}|string> | Header specification | - | | └─ fieldDelimiter | String (Optional) | Field delimiter | , | | └─ recordDelimiter | String (Optional) | Record delimiter | \n |

Returns: ObjectCsvStringifier instance

Contribute

If you'd like to contribute by either proposing new features or reporting bugs, please visit: GitHub Issues

Guidelines

  • Feature Requests: Context is key. Please provide a detailed explanation of why you need the specific feature and how it could benefit the users.

  • Bug Reports: Reproducible code snippets are greatly appreciated.

Development Setup

Requirements

  • Node.js (Version 16 or higher)
  • Docker

License

Licensed under the MIT License.