node.js - Node JS - 递归调用

标签 node.js

所以,我有一个处理目录中文件的应用程序,我希望应用程序继续查看目录中的新文件,如果找到它就会处理它,所以基本上我所做的是当文件不可用时再次调用主函数,这将使我的应用程序保持运行,但我收到错误

错误 RangeError:超出最大调用堆栈大小

这是我的代码片段`在此处输入代码

 function main(){
        const names = scan_dir();
        if(names.length <= 0){
            console.log("nothing found in stage directory");
            main();
            return;
        }else{
            console.log(names.length.toString(), "files found");
        }
// Do something
}

    function scan_dir(){
        const names = fs.readdirSync(STAGE_PATH)`enter code here`;
        return names.filter(name => {
            const abs_name = path.join(STAGE_PATH, name);
            const stats = fs.statSync(abs_name);
            return stats.isFile();
        });
    }

最佳答案

似乎每当它找不到它再次调用该函数时,您都会从中得到一个巨大的堆栈溢出错误。您可以将其放入循环中并迭代执行,这将防止出现此错误。

search = true
while(search){
    names = scan_dir();
    if(names.length <= 0){
       console.log("nothing found in stage directory");
    }else{
       console.log(names.length.toString(), "files found");
       search = false;
    }
}`

关于node.js - Node JS - 递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968406/

相关文章:

android - Cordova安装问题:not installed properly and cordova command is working only on c:\>

javascript - 如何在 azure 上部署和运行 Passport Express Node

node.js - 在运行时向 Mongoose 模型添加默认值

javascript - 加密消息 : Private key is not decrypted 时出错

node.js - 从cmd错误安装react-redux

node.js - 通过 Node 和 Mailchimp API 3.0 将成员添加到 Mailchimp 列表

node.js - 如何在不使用 github 的情况下将我的 nodejs 应用程序部署到 openshift 中?

Javascript/Coffeescript 使用函数哈希作为参数

node.js - 关联搜索 Sequelize

node.js - 首先使用Node和pg创建数据库后如何创建表