同步检查Node.js中是否存在文件/目录 [英] Check synchronously if file/directory exists in Node.js

查看:146
本文介绍了同步检查Node.js中是否存在文件/目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 node.js 同步检查文件或目录是否存在?

How can I synchronously check, using node.js, if a file or directory exists?

推荐答案

多年来,对这个问题的答案已经改变. 当前答案在顶部,其后是按时间顺序排列的多年来的各种答案:

The answer to this question has changed over the years. The current answer is here at the top, followed by the various answers over the years in chronological order:

您可以使用 fs.existsSync() :

You can use fs.existsSync():

const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
    // Do something
}

已弃用了几年,但现在已不再使用.从文档中:

It was deprecated for several years, but no longer is. From the docs:

请注意,已弃用fs.exists(),但未弃用fs.existsSync(). (这 fs.exists()的回调参数接受以下参数 与其他Node.js回调不一致. fs.existsSync()不 使用回调.)

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

您特别要求进行同步检查,但是如果您可以改用异步检查(通常对I/O最好),请使用async函数或 fs.promises.access .org/api/fs.html#fs_fs_access_path_mode_callback"rel =" noreferrer> fs.access (因为

You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access if you're using async functions or fs.access (since exists is deprecated) if not:

async函数中:

try {
    await fs.promises.access("somefile");
    // The check succeeded
} catch (error) {
    // The check failed
}

或带有回调:

fs.access("somefile", error => {
    if (!error) {
        // The check succeeded
    } else {
        // The check failed
    }
});


历史答案

以下是按时间顺序排列的历史答案:


Historical Answers

Here are the historical answers in chronological order:

  • 2010年的原始答案
    (stat/statSynclstat/lstatSync)
  • 2012年9月更新
    (exists/existsSync)
  • 2015年2月更新
    (注意到即将淘汰exists/existsSync,所以我们可能会回到stat/statSynclstat/lstatSync)
  • 2015年12月更新
    (还有fs.access(path, fs.F_OK, function(){})/fs.accessSync(path, fs.F_OK),但请注意,如果文件/目录不存在,则是错误; fs.stat的文档建议使用fs.access,如果您需要在不打开的情况下检查其存在性)
  • 2016年12月更新
    fs.exists()仍被弃用,但fs.existsSync()不再被弃用.因此,您现在可以放心使用它.
  • Original answer from 2010
    (stat/statSync or lstat/lstatSync)
  • Update September 2012
    (exists/existsSync)
  • Update February 2015
    (Noting impending deprecation of exists/existsSync, so we're probably back to stat/statSync or lstat/lstatSync)
  • Update December 2015
    (There's also fs.access(path, fs.F_OK, function(){}) / fs.accessSync(path, fs.F_OK), but note that if the file/directory doesn't exist, it's an error; docs for fs.stat recommend using fs.access if you need to check for existence without opening)
  • Update December 2016
    fs.exists() is still deprecated but fs.existsSync() is no longer deprecated. So you can safely use it now.

您可以使用statSynclstatSync(文档链接),给您一个 fs.Stats对象.通常,如果功能的同步版本可用,则其名称将与异步版本的名称相同,并以Sync结尾.所以statSyncstat的同步版本; lstatSynclstat等的同步版本.

You can use statSync or lstatSync (docs link), which give you an fs.Stats object. In general, if a synchronous version of a function is available, it will have the same name as the async version with Sync at the end. So statSync is the synchronous version of stat; lstatSync is the synchronous version of lstat, etc.

lstatSync告诉您是否存在某些东西,如果存在,则是文件还是目录(或在某些文件系统中,是符号链接,块设备,字符设备等).如果您需要知道它是否存在并且是目录:

lstatSync tells you both whether something exists, and if so, whether it's a file or a directory (or in some file systems, a symbolic link, block device, character device, etc.), e.g. if you need to know if it exists and is a directory:

var fs = require('fs');
try {
    // Query the entry
    stats = fs.lstatSync('/the/path');

    // Is it a directory?
    if (stats.isDirectory()) {
        // Yes it is
    }
}
catch (e) {
    // ...
}

...同样,如果是文件,则为isFile;如果它是块设备,则有isBlockDevice等,请注意.try/catch;如果该条目根本不存在,则会引发错误.

...and similarly, if it's a file, there's isFile; if it's a block device, there's isBlockDevice, etc., etc. Note the try/catch; it throws an error if the entry doesn't exist at all.

如果您不在乎条目是什么,而只想知道它是否存在,则可以使用由user618408 :

If you don't care what the entry is and only want to know whether it exists, you can use path.existsSync (or with latest, fs.existsSync) as noted by user618408:

var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
    // ...
}

它不需要try/catch,但是没有提供任何有关事物的信息,只是它已经存在. path.existsSync很早以前就已弃用.

It doesn't require a try/catch but gives you no information about what the thing is, just that it's there. path.existsSync was deprecated long ago.

旁注:您已明确询问如何同步检查 ,因此我使用了上述功能的xyzSync版本.但是,只要有可能,使用I/O最好避免同步调用.从CPU的角度来看,调用I/O子系统要花费大量时间.请注意,调用 lstat 而不是lstatSync:

Side note: You've expressly asked how to check synchronously, so I've used the xyzSync versions of the functions above. But wherever possible, with I/O, it really is best to avoid synchronous calls. Calls into the I/O subsystem take significant time from a CPU's point of view. Note how easy it is to call lstat rather than lstatSync:

// Is it a directory?
lstat('/the/path', function(err, stats) {
    if (!err && stats.isDirectory()) {
        // Yes it is
    }
});

但是,如果您需要同步版本,就可以使用它.

But if you need the synchronous version, it's there.

以下几年前的答案现在有点过时了.当前方法是使用 fs.existsSync 进行文件/目录存在的同步检查(或者当然是 fs.exists 进行异步检查),而不是path下面的版本.

The below answer from a couple of years ago is now a bit out of date. The current way is to use fs.existsSync to do a synchronous check for file/directory existence (or of course fs.exists for an asynchronous check), rather than the path versions below.

示例:

var fs = require('fs');

if (fs.existsSync(path)) {
    // Do something
}

// Or

fs.exists(path, function(exists) {
    if (exists) {
        // Do something
    }
});

2015年2月更新

现在我们到了2015年,Node文档现在说fs.existsSync(和fs.exists)将被弃用". (因为Node员工认为在打开某个东西之前先检查是否存在某种东西是愚蠢的;但这并不是检查某个东西是否存在的唯一原因!)

Update February 2015

And here we are in 2015 and the Node docs now say that fs.existsSync (and fs.exists) "will be deprecated". (Because the Node folks think it's dumb to check whether something exists before opening it, which it is; but that's not the only reason for checking whether something exists!)

因此,我们很可能会回到各种stat方法...当然,直到/除非再次更改,否则.

So we're probably back to the various stat methods... Until/unless this changes yet again, of course.

不知道它在那里待了多久,但是还有 fs.access(path, fs.F_OK, ...)/fs.accessSync(path, fs.F_OK) .而且至少从2016年10月起, fs.stat文档建议使用fs.access来做是否存在检查(要检查文件是否存在而不随后对其进行操作,建议使用fs.access()." ).但是请注意,访问不可用被认为是错误,因此,如果您期望文件可访问,则可能是最好的选择:

Don't know how long it's been there, but there's also fs.access(path, fs.F_OK, ...) / fs.accessSync(path, fs.F_OK). And at least as of October 2016, the fs.stat documentation recommends using fs.access to do existence checks ("To check if a file exists without manipulating it afterwards, fs.access() is recommended."). But note that the access not being available is considered an error, so this would probably be best if you're expecting the file to be accessible:

var fs = require('fs');

try {
    fs.accessSync(path, fs.F_OK);
    // Do something
} catch (e) {
    // It isn't accessible
}

// Or

fs.access(path, fs.F_OK, function(err) {
    if (!err) {
        // Do something
    } else {
        // It isn't accessible
    }
});

2016年12月更新

您可以使用 fs.existsSync() :

if (fs.existsSync(path)) {
    // Do something
}

它已被弃用了几年,但现在已经不复存在了.从文档中:

It was deprecated for several years, but no longer is. From the docs:

请注意,已弃用fs.exists(),但未弃用fs.existsSync(). (这 fs.exists()的回调参数接受以下参数 与其他Node.js回调不一致. fs.existsSync()不 使用回调.)

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

这篇关于同步检查Node.js中是否存在文件/目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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