如何在Nodejs中编写正确的递归函数?

时间:2018-03-23 20:22:29

标签: node.js

这是我在NodeJS的第一天,我需要编写一个小程序来检查文件和文件夹列表中的某个单词,并打印出包含该单词的文件数组,

我编写了程序,但不幸的是我是以同步方式编写的,不知道NodeJS是异步的,在搜索互联网后我发现了问题,但我仍然无法找到解决方案。

这是我写的代码:

// Get needed arguments for running the script
// USAGE: node search [EXT] [TEXT]
var args = process.argv.slice(2);

if(args[0].length == 0 && args[1].length == 0) { 
    console.log("USAGE: node search [EXT] [TEXT]");
    process.exit();
}

ext_args = args[0];
word_args = args[1];

var fs = require('fs'); // include file reader module
var path = process.cwd(); // get current path of script
var fileList = getFiles(path, ext_args, word_args);
console.log(fileList);
console.log("end");
/*
Function that get files recursively in a current script path
*/
function getFiles(path, ext, word) {
    var fileList = [];
    fs.readdir(path, function(err, items) {
        for (var i=0; i<items.length; i++) {
            var currentFile = items[i];
            var itemPath = path + "\\" + currentFile;
            if(fs.lstatSync(itemPath).isDirectory()) {              
                return getFiles(path + '\\' + currentFile, ext, word);
            } else {
                if(currentFile.endsWith(ext)) {
                   fileList.push(checkString(itemPath, word));
                } else {
                }
            }
        }
    });
    return fileList;
}

/*
 Function that checks if the word exist in the text file
*/
function checkString(filePath, word) {
    fs.readFile(filePath, 'utf8', function(err, data) {
        //console.log("> Checking String");
        if(err) throw err;
        if(data.indexOf(word) >= 0) {           
            return filePath;
        } else {          
        }

    })
}

当我打印fileList时,我将其作为一个空数组。你能告诉我如何以正确的方式编写递归函数吗?

1 个答案:

答案 0 :(得分:1)

您需要使用Async/awaitpromise来处理异步I / O操作,如下所示:

// Get needed arguemnts for running the script
// USAGE: node search [EXT] [TEXT]
var args = process.argv.slice(2);

if (args[0].length == 0 && args[1].length == 0) {
    console.log("USAGE: node search [EXT] [TEXT]");
    process.exit();
}

ext_args = args[0];
word_args = args[1];

var fs = require('fs'); // include file reader module
var path = process.cwd(); // get current path of script
getFiles(path, ext_args, word_args).then((fileList) => {
    console.log(fileList);
    console.log("end");
});
/*
Function that get files recursivly in a current script path
*/
function getFiles(path, ext, word) {
    var fileList = [];
    return new Promise((resolve, reject) => {
        fs.readdir(path, (err, items) => {
            for (var i = 0; i < items.length; i++) {
                var currentFile = items[i];
                var itemPath = path + "\\" + currentFile;
                if (fs.lstatSync(itemPath).isDirectory()) {
                    resolve(getFiles(path + '\\' + currentFile, ext, word));
                } else {
                    if (currentFile.endsWith(ext)) {
                        fileList.push(checkString(itemPath, word));
                    } else {}
                }
            }
        });
        resolve(fileList);
    })
}

/*
 Function that checks if the word exist in the text file
*/
function checkString(filePath, word) {
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, 'utf8', (err, data) => {
            //console.log("> Checking String");
            if (err) {
                reject(err);
            }
            if (data.indexOf(word) >= 0) {
                resolve(filePath);
            }
        })
    })
}