繁体   English   中英

为什么返回在 NodeJS/Electron 中不起作用

[英]Why return doesn't work in NodeJS/Electron

我的 NodeJS 脚本有问题。 基本上我想将每个文件路径添加到一个数组中,然后在 bash 控制台中显示它。 但是当我尝试时,它给了我undefined

这是我的代码:

const { app, BrowserWindow } = require('electron');
const fs = require('fs');
const path = require('path');

function repList(){
    var directoryPath = path.join('Q:/Programmes');
    let forbiddenDir = [".VERSIONS", "INSTALL"];
    fs.readdir(directoryPath, function (err, files) { //Scans the files in the directory
        if (err) {
            return console.log('Unable to scan directory: ' + err);
        }
        else{
            files.forEach(function (file){ //Loops through each file
                var name = directoryPath+"/"+file;
                if(forbiddenDir.includes(file)){ //Don't accept the file if unvalid
                    console.log(`${file} is a forbidden name.`);
                }
                else{ //Filename is valid
                    fs.stat(name, (error, stats) => {
                        if (stats.isDirectory()) { //If directory...
                            tabRep.push(name); //... add the full filename path to the tabRep array
                        }
                        else if (error) {
                            console.error(error);
                        }
                    });
                };
            }); //End of loop
            return tabRep; //<-- THIS RETURN DOESN'T WORK
        }
    });
}

app.whenReady().then(() => {
    console.log(repList());
})

它给了我这个输出而不是tabRep的元素:

不明确的
.VERSIONS 是一个被禁止的名字。
INSTALL 是一个被禁止的名字。

Programmes文件夹中:

\\ 程式

\\ .VERSIONS
\\文件夹1
\\文件1
\\文件夹2
\\ 安装
\\文件夹N
\\文件N

如果有人能给我一些帮助,那将不胜感激。

fs.readdir()需要一个回调函数作为第二个参数(你传递了它)。 return你指向是回调函数的返回-而不是返回repList()函数。 请阅读 JavaScript 中的异步函数和回调以完全理解这个概念,因为这在 JavaScript 中非常重要。 此外,您的函数repList()不返回任何内容! 我认为缺少变量tabRep声明。

长期以来, fs.readdirSync()的同步变体,如下所示:

const { app, BrowserWindow } = require('electron');
const fs = require('fs');
const path = require('path');

function repList(){
    var directoryPath = path.join('Q:/Programmes');
    let forbiddenDir = [".VERSIONS", "INSTALL"];
    const files = fs.readdirSync(directoryPath)
    const tabRep = []

    files.forEach(function (file){ //Loops through each file
        var name = directoryPath+"/"+file;
        if(forbiddenDir.includes(file)){ //Don't accept the file if unvalid
            console.log(`${file} is a forbidden name.`);
        }
        else{ //Filename is valid
            const stats = fs.statSync(name)
            if (stats.isDirectory()) { //If directory...
                tabRep.push(name); //... add the full filename path to the tabRep array
            }
        }
    }); //End of loop
    return tabRep; //<-- THIS RETURN DOES WORK NOW since now the function executes synchronously.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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