簡體   English   中英

為什么在節點中運行的.js文件中遇到foreach未定義錯誤,我該如何解決?

[英]Why am I encountering a foreach undefined error in this .js file running in node.. and how can I fix it?

我在節點上運行以下myfile.js。
這樣執行..節點myfile.js

但是,這會導致forEach未定義錯誤...我也認為我的語法也是正確的! 我想念什么嗎?

我得到的錯誤是... TypeError:無法讀取未定義的屬性'forEach'

var fs = require('fs');
var path = require('path');
fs.readdir("/.lib", function(err,files){

    files.forEach(function(fileName) {
        var file = path.join(__dirname, "lib", fileName);
        var stats = fs.statSync(file);

        if (stats.isFile() && fileName !== ".DS_Store"){

            fs.readFile(file,"UTF-8", function(err,contents){
                console.log(contents);
            });

        };
    });

});

請在下面查看我的示例,以了解如何改進代碼。 首先,我檢查了該文件夾是否存在,然后必須確保引發了錯誤,然后檢查是否有文件。

 var fs = require('fs'); var path = require('path'); var searchPath = './lib'; if (fs.existsSync(searchPath)) { // `existsSync` is recommended to be used. `exists` is deprecated fs.readdir(searchPath, function(err, files) { if (err) { // fix error throw err; } if (!files.length) { console.log('Empty folder'); } else { files.forEach(function(fileName) { var file = path.join(__dirname, "lib", fileName); var stats = fs.statSync(file); var excludeFiles = ['.DS_Store'] if (stats.isFile() && excludeFiles.indexOf(fileName) === -1) { fs.readFile(file, "UTF-8", function(err, contents) { console.log(contents); }); }; }); } }); } else { console.log('Folder doesn\\'t exist') } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM