Last active
August 29, 2015 14:04
-
-
Save rwilcox/e8411242ffe4f06af35c to your computer and use it in GitHub Desktop.
Using the CSV NPM Package, turn objects into CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# An example project showing how to write objects using the CSV npm package | |
csv = require 'csv' | |
util = require 'util' | |
# Use the callback API to write this | |
callback_generate_csv_from_list = (records_to_write, cb) -> | |
map_reduce_it = [] | |
for current_profile in profile_list | |
map_reduce_it.push( [current_profile.name | |
, current_profile.category_name | |
, current_profile.brand?.name] ) | |
csv.stringify(map_reduce_it, {header: true, columns: ["Name", "Category", "Brand"]}, cb) | |
# Use the streaming API to write this | |
streaming_generate_csv_from_list = (records_to_write, writable_stream) -> | |
stringer = csv.stringify({header: true, columns: ["Name", "Category", "Brand"]}) | |
stringer.on 'readable', () -> | |
while(data = stringer.read()) | |
writable_stream.write(data) | |
for current_profile in profile_list | |
#console.log "processing current item: #{current_profile}" | |
stringer.write [current_profile.name | |
, current_profile.category_name | |
, current_profile.brand?.name] | |
stringer.end() | |
profile_list = [ {name: "Macbook Pro, Retina", category_name: "Computer", brand: {name: "Apple"}}, | |
{name: "Macbook Pro", category_name: "Computer", brand: {name: "Apple"}}, | |
{name: "Acer 1", category_name: "Netbook", brand: {name: "Acer"}} ] | |
use_callback = true | |
if use_callback | |
callback_generate_csv_from_list profile_list, (err, data) -> | |
if err? | |
console.write "ERROR!" | |
else | |
process.stdout.write data | |
process.exit() | |
else | |
streaming_generate_csv_from_list profile_list, process.stdout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment