我只想知道路径是否存在。这是我的代码:
var path = require('path'); // exists path
我只想知道路径是否存在。这是我的代码:
var path = require('path'); // exists path
使用fs.existsSync()
方法来检查文件系统中是否存在一个文件的方式:
const fs = require('fs')
const path = './file.txt';
if (fs.existsSync(path)) {
//file exists
}
这个方法是同步的,要以异步方式检查文件是否存在,可以使用 fs.access()
,它可以在不打开文件的情况下检查文件是否存在:
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err)
return
}
//file exists
})
path.exists()
在0.8.0及更高版本中已被弃用。请改用fs.exists()
。 - ebohlmanpath
作为全局字符串使用,这与其被引用为require('path')
的约定冲突。 - 1owk3ypath
作为全局字符串使用,这与它通常被引用为require('path')
的约定冲突。 - undefined
fs.readFile()
而不先检查文件是否存在...(原因在于文件可能存在,但当你去访问它时,它可能已经不存在等等。) - Andrew