I'm using node-csv-parser by wdavidw with coffeescript. I know (or should know) about variables scope, bind, globals, but looking at this code snippet I couldn't understood what do @array varable lose its values or even be assigned.
script.coffee:
require 'csv'
find_lines = ->
@array = []
csv()
.fromPath("#{__dirname}/Cities.csv", {delimiter:";"})
.on 'data', (data, index) =>
@array = data
console.log @array
find_lines()
Running the script.coffe:
➜ modules git:(master) ✗ coffee script.coffee
The code output is:
quoted false
quoted false
quoted false
quoted false
When it should be (according to csv values):
City 1
City 2
City 3
Using the .transform method from csv parser produces the same error.
Did I misunderstand how node-csv-parser works or any problem with this module?
Thanks in advance!
Let's start with one possible implementation:
csv = require 'csv'
find_lines = ->
array = []
csv()
.fromPath("#{__dirname}/Cities.csv", {delimiter:";"})
.on 'data', (data) ->
array.push data[0]
.on 'end', ->
console.log array
find_lines()
Note that you probably want something other than array.push data[0]
in the 'data' callback.
You don't need to use @array
here because the array
variable is available to the 'data' and 'end' callbacks. This also eliminates the need for the fat arrow function bindings. In this implementation, the array
variable is only visible in the scope of find_lines
so you won't be able to log its contents from outside the function call.
Alternatively, you can make array
visible outside of find_lines
by moving it to the module scope like so:
csv = require 'csv'
array = []
find_lines = ->
csv()
...
However, (and this is the really critical point), the array
variable will not be modified until after the rest of your module code (including any calls to console.log
outside of find_lines
) has already executed. If this is unclear, you should brush up on the fundamentals of callbacks and execution order in node.js.
require 'csv'
should be csv = require 'csv'
array
was not being modified with data
, it was being overwritten on each new csv row