如何使用Node.js检查一个文件是否存在于文件系统中,使用`fs`模块
使用Node.js检查文件系统中是否存在一个文件的方法是使用fs.existsSync() 方法。
const fs = require('fs')
const path = './file.txt'
try {
if (fs.existsSync(path)) {
//file exists
}
} catch(err) {
console.error(err)
}
这个方法是同步的。这意味着它是阻塞的。要以异步方式检查一个文件是否存在,你可以使用fs.access() ,它在不打开文件的情况下检查文件的存在。
const fs = require('fs')
const path = './file.txt'
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err)
return
}
//file exists
})