0

I'm trying to learn javascript to work with node.js and obviously don't quite get closures. I'm try to read a file, line by line, parse the line and put the result into an array and return the array. Here's what I have (doesn't quite work):

var fs = require('fs'), Lazy = require('lazy');

function parseMyFile (filename) {
    var myArray= [];
    var lazy = new Lazy (fs.createReadStream(filename));

    lazy
        .lines
        .map(function(line){
            var parts = line.toString().split('|');

            var item = {
              bucket:   parts[1],
              uri:      parts[2].substring(2),
              token:    parts[0],
              fileDate: parts[3]
           };          

           myArray.push (item);
        });

     console.log(myArray);  // empty

         return myArray;
};


var myItems = parseMyFile ('Tokens.csv');

I'm sure this has something to do with closures, just not quite getting it. Any help would be appreciated.

Thanks!

7
  • Please elaborate on "doesn't quite work". Commented Aug 7, 2012 at 13:09
  • 2
    The code itself seems correct...did you check doing a console.log(line) if the map it's doing what it should? Commented Aug 7, 2012 at 13:10
  • @Deestan it's the OP's code, but not the question text: "console.log(myArray); // empty". The OP expects myArray to be non-empty, when it is empty. Commented Aug 7, 2012 at 13:11
  • Looks about right for me concerning the array part. But isn't the line parameter already a string? does parts contain an array when it is created? Commented Aug 7, 2012 at 13:11
  • 1
    @Nicosunshine the code is "correct" in that there aren't syntax errors, but it's written such that it assumes the asynchronous completion of the file I/O will happen synchronously. Commented Aug 7, 2012 at 13:14

1 Answer 1

1

It's a lazy list. It's a wrapper around asynchronous behavior. You're trying to examine the list before it's been filled in, so of course it doesn't work.

The problem has nothing to do with closures. It's all about asynchronous behavior.

I don't see anything in that lazy list code that allows a generic "when finished" callback.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.