Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

node.js - 同步检查Node.js中是否存在文件/目录(Check synchronously if file/directory exists in Node.js)

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

  ask by Ragnis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

(当前答案在顶部,其后是按时间顺序排列的多年来的各种答案:)

Current Answer (当前答案)

You can use fs.existsSync() :

(您可以使用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:

(从文档:)

Note that fs.exists() is deprecated, but fs.existsSync() is not.

(请注意,不建议使用fs.exists() ,但不建议使用fs.existsSync() 。)

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

(( fs.exists()的回调参数接受与其他Node.js回调不一致的参数fs.existsSync()不使用回调。))

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:

(你特别要求同步检查,但如果你能使用异步检查,而不是(通常是最好的I / O),使用fs.promises.access如果你使用async函数或fs.access (因为exists已过时 ) 如果不:)

In an async function:

(在async函数中:)

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

Or with a callback:

(或使用回调:)

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

Historical Answers (历史答案)

Here are the historical answers in chronological order:

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

  • Original answer from 2010

    (2010年的原始答案)
    ( stat / statSync or lstat / lstatSync )

    (( stat / statSynclstat / lstatSync ))

  • Update September 2012

    (2012年9月更新)
    ( exists / existsSync )

    (( exists / exists existsSync ))

  • Update February 2015

    (2015年2月更新)
    (Noting impending deprecation of exists / existsSync , so we're probably back to stat / statSync or lstat / lstatSync )

    ((注意到即将弃用exists / existsSync ,所以我们可能回到stat / statSynclstat / lstatSync ))

  • Update December 2015

    (2015年12月更新)
    (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)

    ((还有fs.access(path, fs.F_OK, function(){}) / fs.accessSync(path, fs.F_OK) ,但请注意,如果文件/目录不存在,则是错误;请参阅如果需要在不打开的情况下检查是否存在,则fs.stat建议使用fs.access ))

  • Update December 2016

    (2016年12月更新)
    fs.exists() is still deprecated but fs.existsSync() is no longer deprecated.

    (fs.exists()仍然被弃用,但fs.existsSync()不再被弃用。)

    So you can safely use it now.

    (因此,您现在可以安全使用它。)

Original answer from 2010: (2010年的原始答案:)

You can use statSync or lstatSync ( docs link ), which give you an fs.Stats object .

(您可以使用statSynclstatSync文档链接 ),这将为您提供fs.Stats对象 。)

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.

(通常,如果功能的同步版本可用,则其名称将与带有Sync末尾的异步版本的名称相同。)

So statSync is the synchronous version of stat ;

(因此statSyncstat的同步版本;)

lstatSync is the synchronous version of lstat , etc.

(lstatSynclstat等的同步版本。)

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.), eg if you need to know if it exists and is a directory:

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

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) {
    // ...
}

...and similarly, if it's a file, there's isFile ;

(...同样,如果是文件,则有isFile ;)

if it's a block device, there's isBlockDevice , etc., etc. Note the try/catch ;

(如果是块设备,则有isBlockDevice等,等等。请注意try/catch ;)

it throws an error if the entry doesn't exist at all.

(如果该条目根本不存在,则会引发错误。)

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 :

(如果您不在乎条目什么,而只想知道条目是否存在,则可以使用path.existsSync 指出的path.existsSync (或使用最新的fs.existsSync ):)

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

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

(它不需要try/catch但没有提供有关事物内容的任何信息,只是它在那里。)

path.existsSync was deprecated long ago.

(path.existsSync很久以前不推荐使用。)


Side note: You've expressly asked how to check synchronously , so I've used the xyzSync versions of the functions above.

(旁注:您已经明确询问了如何同步检查,因此我使用了上述功能的xyzSync版本。)

But wherever possible, with I/O, it really is best to avoid synchronous calls.

(但是,只要有可能,使用I / O最好避免同步调用。)

Calls into the I/O subsystem take significant time from a CPU's point of view.

(从CPU的角度来看,调用I / O子系统要花费大量时间。)

Note how easy it is to call lstat rather than lstatSync :

(注意调用lstat而不是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.

(但是,如果您需要同步版本,则可以使用它。)

Update September 2012 (2012年9月更新)

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.

(当前的方法是使用fs.existsSync进行文件/目录是否存在的同步检查(或者当然是fs.exists进行异步检查),而不是下面的path版本。)

Example:

(例:)

<cod

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...