[英]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.