同步检查 Node.js 中是否存在文件/目录 [英] Check synchronously if file/directory exists in 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()
:
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, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
您明确要求进行同步检查,但如果您可以使用异步检查代替(通常最适合 I/O),请使用 fs.promises.access
如果您使用的是 async
函数或 fs.access
(因为 exists
已弃用) 如果不是:
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
/statSync
或lstat
/lstatSync
) - 2012 年 9 月更新
(exists
/existsSync
) - 2015 年 2 月更新
(注意到exists
/existsSync
即将被弃用,所以我们可能会回到stat
/statSync
或lstat
/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
orlstat
/lstatSync
) - Update September 2012
(exists
/existsSync
) - Update February 2015
(Noting impending deprecation ofexists
/existsSync
, so we're probably back tostat
/statSync
orlstat
/lstatSync
) - Update December 2015
(There's alsofs.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 forfs.stat
recommend usingfs.access
if you need to check for existence without opening) - Update December 2016
fs.exists()
is still deprecated butfs.existsSync()
is no longer deprecated. So you can safely use it now.
您可以使用 statSync
或 lstatSync
(docs 链接),它给你一个 fs.Stats
对象.通常,如果函数的同步版本可用,它将与异步版本具有相同的名称,并以 Sync
结尾.所以statSync
是stat
的同步版本;lstatSync
是lstat
等的同步版本
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.
如果你不关心条目是什么而只想知道它是否存在,你可以使用path.existsSync
(或最新的fs.existsSync
)作为由用户 618408 注释:
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, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
这篇关于同步检查 Node.js 中是否存在文件/目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!