简体   繁体   中英

Wondering how to debug Node.js learnyounode “filter ls” exercise

I'm working through the learnyounode exercises. Specifically "filter ls". If you're not familiar with this exercise please refer to this description of it.

Here is the official solution :

var fs = require('fs');
var path = require('path');
fs.readdir(process.argv[2], function (err, list) {
  list.forEach(function (filename) {
    if (path.extname(filename) === '.' + process.argv[3]) {
      console.log(filename);
    }
  });
});

Here is my solution:

var fs = require('fs');
var path = require('path');
var directory = process.argv[2];
var fileExtension = "." + process.argv[3];

function sortFiles (callback){

    fs.readdir(directory, function(err,files){

        if(err) return callback(err);

        callback(null,files);
    });
};

sortFiles(function(err,files){
    var fileExt = "";
    for(var i = 0; i < files; i++){
        debugger;
        fileExt = path.extname(files[i]);

        if(fileExt === fileExtension){
            console.log(files[i]);
        };
    };
});

The problem:

My code outputs nothing. As far as I can tell, there biggest difference between my code and the official solution is the following:

      list.forEach(function (filename) {
        if (path.extname(filename) === '.' + process.argv[3]) {
        console.log(filename);
      }

vs:

    for(var i = 0; i < files; i++){

        fileExt = path.extname(files[i]);

        if(fileExt === fileExtension){
            console.log(files[i]);
        };
    };

2 Questions:

1) How do I debug this code? I tried node debug node.js . From that I can see that when my directory is a folder that contains a cs file and a js file, files is an array, but each index contains "".

2) Why is my approach of a simple for loop not working? Why did they chose .foreach ? Is there any reason other than it being more terse?

1) https://github.com/node-inspector/node-inspector

2) Forgot to check the length :

for(var i = 0; i < files.length; i++){
                         --^--

But forEach reads better, and it is more idiomatic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM