如何使用nodejs确定目录是否为空目录 [英] how to determine whether the directory is empty directory with nodejs

查看:1607
本文介绍了如何使用nodejs确定目录是否为空目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了Nodejs文档,但是没有找到相关的API.

I have searched the Nodejs Doc,But don't find relative API.

因此,我编写以下代码来确定目录是否为空目录.

So I write the following code to determine whether the directory is empty directory.

var fs = require('fs');

function isEmptyDir(dirnane){
    try{
        fs.rmdirSync(dirname)
    }
    catch(err){
        return false;
    }
    fs.mkdirSync(dirname);
    return true
}

问题:看起来有些麻烦,有更好的方法使用nodejs吗?

推荐答案

我想我想知道为什么您不只是列出目录中的文件,看看是否能找回文件?

I guess I'm wondering why you don't just list the files in the directory and see if you get any files back?

fs.readdir(dirname, function(err, files) {
    if (err) {
       // some sort of error
    } else {
       if (!files.length) {
           // directory appears to be empty
       }
    }
});

您当然也可以为此做一个同步版本.

You could, of course, make a synchronous version of this too.

这当然不能保证目录中没有任何内容,但这确实意味着您没有权限查看其中的公共文件.

This, of course, doesn't guarantee that there's nothing in the directory, but it does mean there are no public files that you have permission to see there.

以下是功能形式的promise版本,用于新版本的nodejs:

Here's a promise version in a function form for newer versions of nodejs:

function isDirEmpty(dirname) {
    return fs.promises.readdir(dirname).then(files => {
        return files.length === 0;
    });
}

这篇关于如何使用nodejs确定目录是否为空目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆