Skip to content

Instantly share code, notes, and snippets.

@rwilcox
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwilcox/e8411242ffe4f06af35c to your computer and use it in GitHub Desktop.
Save rwilcox/e8411242ffe4f06af35c to your computer and use it in GitHub Desktop.
Using the CSV NPM Package, turn objects into CSV
# 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