简体   繁体   English

节点:fs.readdir() 总是返回文件

[英]Node: fs.readdir() always returns files

I have this code snippet:我有这个代码片段:

fs.readdir(STLFilesDir, (err, files) => {
            if (err)
            {
                console.log(err);
                throw err;
            }
            if (files)
            {
                console.log(files); //files is an array with all the files in the directory
                res.render('prerenderer.ejs');
            }   
            else 
            {
                console.log('no files found');
                res.render('prerenderer.ejs');
            }

However, in the case of not having any files in the folder, I dont't get what is expected.但是,在文件夹中没有任何文件的情况下,我没有得到预期的结果。 Instead of seeing no files found, in the console.而不是在控制台中看到没有找到文件。 I get this [] .我得到这个[] This is an empty object.这是一个空对象。 This means that the last else does not work.这意味着最后一个else不起作用。 So fs.readdir() always returns an array - even if it's empty.所以fs.readdir()总是返回一个数组——即使它是空的。 So how can I get the else portion to run?那么我怎样才能让else部分运行呢?

在javascript中,空数组[]真的,所以你需要if (files.length)而不是if (files)

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

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