【问题标题】:node js - module scope with variables and results of a functionnode js - 具有变量和函数结果的模块范围
【发布时间】:2013-11-12 04:05:51
【问题描述】:

我需要一些帮助来理解如何从我想作为 module.exports 传递的函数中复制结果。这里存在全局和本地范围的问题:

// Declare node.js module dependencies from API
var walk = require('walk'), 
    filter;

// Declare variables    
var files = []; 
var filteredFiles = []; 
var i = 0;
var fileextension = '.html';
var foldername = 'node_modules';
var filter = {
    followLinks: false
};
var walker = walk.walkSync(foldername, filter); 

var temp = [];

module.exports = {
    scanDirWithFil: function () {
        walker.on('file', function(root, stat, next) {
            files.push(stat.name);
            if (files[i].indexOf(fileextension) != -1) { 
                filteredFiles.push(stat.name);
                console.log(files[i]);
                next();
                i++;
            }
            else { 
                next();
                i++;
            }
            console.log('Number of filtered files in array: ' + filteredfiles.length + ", Total number of files in array: " + files.length)
            return files, filteredFiles;
        });
        temp = files.toString();
        return temp;
    }
};

正如您在此处看到的,我正在尝试返回函数 scanDirWithFil 的结果,但是返回是通过 temp 的,它来自 files.toString。这就是问题所在。由于范围问题,文件现在变成了一个空数组。从 walker.on 方法返回的 files 数组实际上并没有超出其自身范围。

如果我说的是对的(这是范围问题).. 有人可以指导我或帮助我解决这个问题吗?

谢谢你, 布赖恩

【问题讨论】:

    标签: arrays node.js module scope tostring


    【解决方案1】:

    查看文档,显然调用 walker.on 会导致代码异步运行。所以这不是范围问题,而是在 walker 函数执行之前简单地执行行 temp = files.toString()。因此,files 数组为空是唯一合乎逻辑的。

    为了在同步模式下使用walker,您需要做:

    walker = walk.walkSync("/tmp", {
        listeners: {
            file: function (root, fileStats, next) {
    
            }
        }
    });
    

    见:https://github.com/coolaj86/node-walk

    【讨论】:

    • 非常感谢!所以这是因为代码是异步运行的。很高兴知道。
    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多