关于学习节点练习5的问题

problems on learnyounode exercise 5

本文关键字:练习 问题 节点 于学习 学习      更新时间:2023-09-26

大家好,我正在尝试解决nodesschool的练习,我从learnyounode开始,人们向初学者推荐很多,练习问题是:

# LEARN YOU THE NODE.JS FOR MUCH WIN!
## FILTERED LS (Exercise 5 of 13)
 Create a program that prints a list of files in a given directory,
 filtered by the extension of the files. You will be provided a directory
 name as the first argument to your program (e.g. '/path/to/dir/') and a
 file extension to filter by as the second argument.
 For example, if you get 'txt' as the second argument then you will need to
 filter the list to only files that end with .txt. Note that the second
 argument will not come prefixed with a '.'.
 Keep in mind that the first arguments of your program are not the first
 values of the process.argv array, as the first two values are reserved for
 system info by Node.
 The list of files should be printed to the console, one file per line. You
 must use asynchronous I/O.
─────────────────────────────────────────────────────────────────────────────

## HINTS
 The fs.readdir() method takes a pathname as its first argument and a
 callback as its second. The callback signature is:
    function callback (err, list) { /* ... */ }
 where list is an array of filename strings.
 Documentation on the fs module can be found by pointing your browser here:
 file://C:'Users'Filipe'AppData'Roaming'npm'node_modules'learnyounode'node_
 apidoc'fs.html
 You may also find node's path module helpful, particularly the extname
 method.
 Documentation on the path module can be found by pointing your browser
 here:
 file://C:'Users'Filipe'AppData'Roaming'npm'node_modules'learnyounode'node_
 apidoc'path.html
─────────────────────────────────────────────────────────────────────────────

  » To print these instructions again, run: learnyounode print
  » To execute your program in a test environment, run: learnyounode run
    program.js
  » To verify your program, run: learnyounode verify program.js
  » For help run: learnyounode help

我尝试这样做来解决练习:

var fs = require('fs');
fs.readdir(process.argv[2],process.argv[3],function(err,list){
    for(var i = 0;i<list.length;i++)
    {
        var fileParts = list[i].split(".");
        if(fileParts[1] == process.argv[3]){
            console.log(list[i] + "'n");
        }
    }
});

为什么它不工作,我不知道我做错了什么,如果有人能给我一个技巧来解决这个问题,我很感激,因为网络上的解决方案有点奇怪

嗯,我刚刚测试了你的代码,它实际上运行得很好。用已解决的方法验证退货。不知道你在经历什么。顺便说一句。:至少加入一些错误处理。

const fs = require('fs');
const test = '.' + process.argv[3]
fs.readdir(process.argv[2], (err, data) => {
    if (err) { 
        console.error(err); 
    } else {
        data.filter(file => {
            if (file.substring(file.length - test.length) === test) {
                console.log(file)
            }
        })  
    }
});