UNPKG

8.37 kBMarkdownView Raw
1[![Build Status](https://travis-ci.org/ryu1kn/csv-writer.svg?branch=master)](https://travis-ci.org/ryu1kn/csv-writer)
2[![Coverage Status](https://coveralls.io/repos/github/ryu1kn/csv-writer/badge.svg?branch=master)](https://coveralls.io/github/ryu1kn/csv-writer?branch=master)
3[![Code Climate](https://codeclimate.com/github/ryu1kn/csv-writer/badges/gpa.svg)](https://codeclimate.com/github/ryu1kn/csv-writer)
4
5# CSV Writer
6
7Convert objects/arrays into a CSV string or write them into a file.
8It respects [RFC 4180](https://tools.ietf.org/html/rfc4180) for the output CSV format.
9
10## Prerequisite
11
12* Node version 4 or above
13
14## Usage
15
16The example below shows how you can write records defined as the array of objects into a file.
17
18```js
19const createCsvWriter = require('csv-writer').createObjectCsvWriter;
20const csvWriter = createCsvWriter({
21 path: 'path/to/file.csv',
22 header: [
23 {id: 'name', title: 'NAME'},
24 {id: 'lang', title: 'LANGUAGE'}
25 ]
26});
27
28const records = [
29 {name: 'Bob', lang: 'French, English'},
30 {name: 'Mary', lang: 'English'}
31];
32
33csvWriter.writeRecords(records) // returns a promise
34 .then(() => {
35 console.log('...Done');
36 });
37
38// This will produce a file path/to/file.csv with following contents:
39//
40// NAME,LANGUAGE
41// Bob,"French, English"
42// Mary,English
43```
44
45You can keep writing records into the same file by calling `writeRecords` multiple times
46(but need to wait for the fulfillment of the `promise` of the previous `writeRecords` call).
47
48```js
49// In an `async` function
50await csvWriter.writeRecords(records1)
51await csvWriter.writeRecords(records2)
52...
53```
54
55However, if you need to keep writing large data to a certain file, you would want to create
56node's transform stream and use `CsvStringifier`, which is explained later, inside it
57, and pipe the stream into a file write stream.
58
59If you don't want to write a header line, don't give `title` to header elements and just give field IDs as a string.
60
61```js
62const createCsvWriter = require('csv-writer').createObjectCsvWriter;
63const csvWriter = createCsvWriter({
64 path: 'path/to/file.csv',
65 header: ['name', 'lang']
66});
67```
68
69If each record is defined as an array, use `createArrayCsvWriter` to get an `csvWriter`.
70
71```js
72const createCsvWriter = require('csv-writer').createArrayCsvWriter;
73const csvWriter = createCsvWriter({
74 header: ['NAME', 'LANGUAGE'],
75 path: 'path/to/file.csv'
76});
77
78const records = [
79 ['Bob', 'French, English'],
80 ['Mary', 'English']
81];
82
83csvWriter.writeRecords(records) // returns a promise
84 .then(() => {
85 console.log('...Done');
86 });
87
88// This will produce a file path/to/file.csv with following contents:
89//
90// NAME,LANGUAGE
91// Bob,"French, English"
92// Mary,English
93```
94
95If you just want to get a CSV string but don't want to write into a file,
96you can use `createObjectCsvStringifier` (or `createArrayCsvStringifier`)
97to get an `csvStringifier`.
98
99```js
100const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
101const csvStringifier = createCsvStringifier({
102 header: [
103 {id: 'name', title: 'NAME'},
104 {id: 'lang', title: 'LANGUAGE'}
105 ]
106});
107
108const records = [
109 {name: 'Bob', lang: 'French, English'},
110 {name: 'Mary', lang: 'English'}
111];
112
113console.log(csvStringifier.getHeaderString());
114// => 'NAME,LANGUAGE\n'
115
116console.log(csvStringifier.stringifyRecords(records));
117// => 'Bob,"French, English"\nMary,English\n'
118```
119
120
121## API
122
123### createObjectCsvWriter(params)
124
125##### Parameters:
126
127* params `<Object>`
128 * path `<string>`
129
130 Path to a write file
131
132 * header `<Array<{id, title}|string>>`
133
134 Array of objects (`id` and `title` properties) or strings (field IDs).
135 A header line will be written to the file only if given as an array of objects.
136
137 * fieldDelimiter `<string>` (optional)
138
139 Default: `,`. Only either comma `,` or semicolon `;` is allowed.
140
141 * recordDelimiter `<string>` (optional)
142
143 Default: `\n`. Only either LF (`\n`) or CRLF (`\r\n`) is allowed.
144
145 * headerIdDelimiter `<string>` (optional)
146
147 Default: `undefined`. Give this value to specify a path to a value in a nested object.
148
149 * alwaysQuote `<boolean>` (optional)
150
151 Default: `false`. Set it to `true` to double-quote all fields regardless of their values.
152
153 * encoding `<string>` (optional)
154
155 Default: `utf8`.
156
157 * append `<boolean>` (optional)
158
159 Default: `false`. When `true`, it will append CSV records to the specified file.
160 If the file doesn't exist, it will create one.
161
162 **NOTE:** A header line will not be written to the file if `true` is given.
163
164##### Returns:
165
166* `<CsvWriter>`
167
168
169### createArrayCsvWriter(params)
170
171##### Parameters:
172
173* params `<Object>`
174 * path `<string>`
175
176 Path to a write file
177
178 * header `<Array<string>>` (optional)
179
180 Array of field titles
181
182 * fieldDelimiter `<string>` (optional)
183
184 Default: `,`. Only either comma `,` or semicolon `;` is allowed.
185
186 * recordDelimiter `<string>` (optional)
187
188 Default: `\n`. Only either LF (`\n`) or CRLF (`\r\n`) is allowed.
189
190 * alwaysQuote `<boolean>` (optional)
191
192 Default: `false`. Set it to `true` to double-quote all fields regardless of their values.
193
194 * encoding `<string>` (optional)
195
196 Default: `utf8`.
197
198 * append `<boolean>` (optional)
199
200 Default: `false`. When `true`, it will append CSV records to the specified file.
201 If the file doesn't exist, it will create one.
202
203 **NOTE:** A header line will not be written to the file if `true` is given.
204
205##### Returns:
206
207* `<CsvWriter>`
208
209
210### CsvWriter#writeRecords(records)
211
212##### Parameters:
213
214* records `<Iterator<Object|Array>>`
215
216 Depending on which function was used to create a `csvWriter` (i.e. `createObjectCsvWriter` or `createArrayCsvWriter`),
217 records will be either a collection of objects or arrays. As long as the collection is iterable, it doesn't need to be an array.
218
219##### Returns:
220
221* `<Promise>`
222
223
224### createObjectCsvStringifier(params)
225
226##### Parameters:
227
228* params `<Object>`
229 * header `<Array<{id, title}|string>>`
230
231 Array of objects (`id` and `title` properties) or strings (field IDs)
232
233 * fieldDelimiter `<string>` (optional)
234
235 Default: `,`. Only either comma `,` or semicolon `;` is allowed.
236
237 * recordDelimiter `<string>` (optional)
238
239 Default: `\n`. Only either LF (`\n`) or CRLF (`\r\n`) is allowed.
240
241 * headerIdDelimiter `<string>` (optional)
242
243 Default: `undefined`. Give this value to specify a path to a value in a nested object.
244
245 * alwaysQuote `<boolean>` (optional)
246
247 Default: `false`. Set it to `true` to double-quote all fields regardless of their values.
248
249##### Returns:
250
251* `<ObjectCsvStringifier>`
252
253### ObjectCsvStringifier#getHeaderString()
254
255##### Returns:
256
257* `<string>`
258
259### ObjectCsvStringifier#stringifyRecords(records)
260
261##### Parameters:
262
263* records `<Array<Object>>`
264
265##### Returns:
266
267* `<string>`
268
269### createArrayCsvStringifier(params)
270
271##### Parameters:
272
273* params `<Object>`
274 * header `<Array<string>>` (optional)
275
276 Array of field titles
277
278 * fieldDelimiter `<string>` (optional)
279
280 Default: `,`. Only either comma `,` or semicolon `;` is allowed.
281
282 * recordDelimiter `<string>` (optional)
283
284 Default: `\n`. Only either LF (`\n`) or CRLF (`\r\n`) is allowed.
285
286 * alwaysQuote `<boolean>` (optional)
287
288 Default: `false`. Set it to `true` to double-quote all fields regardless of their values.
289
290##### Returns:
291
292* `<ArrayCsvStringifier>`
293
294### ArrayCsvStringifier#getHeaderString()
295
296##### Returns:
297
298* `<string>`
299
300### ArrayCsvStringifier#stringifyRecords(records)
301
302##### Parameters:
303
304* records `<Array<Array<string>>>`
305
306##### Returns:
307
308* `<string>`
309
310
311## Request Features or Report Bugs
312
313Feature requests and bug reports are very welcome: https://github.com/ryu1kn/csv-writer/issues
314
315A couple of requests from me when you raise an issue on GitHub.
316
317* **Requesting a feature:** Please try to provide the context of why you want the feature. Such as,
318 in what situation the feature could help you and how, or how the lack of the feature is causing an inconvenience to you.
319 I can't start thinking of introducing it until I understand how it helps you 🙂
320* **Reporting a bug:** If you could provide a runnable code snippet that reproduces the bug, it would be very helpful!
321
322
323## Development
324
325### Prerequisite
326
327* Node version 8 or above
328* Docker