fs-extra 中的 pathExists() 函数 - NodeJS
异步简介pathExists()
此方法将通过检查文件系统来测试给定路径是否存在。如果路径不存在,它会在回调中抛出错误。
语法
pathExists(file[, callback])
参数
file-这是需要在所有文件系统中检查的文件的路径。
callback-如果发生任何错误,此函数将提供回调。
例子
在继续之前检查fs-extra是否已安装;如果没有,请安装fs-exra。
您可以使用以下命令来检查是否安装了fs-extra。
npm ls fs-extra
创建一个pathExists.js并将以下代码片段复制粘贴到该文件中。
现在,运行以下命令来运行以下代码片段。
node pathExists.js
代码片段
const fs = require('fs-extra')
const file = '/tmp/dest/file2.txt'
//使用回调检查路径:
fs.pathExists(file, (err, exists) => {
console.log(err) // => This will be null
console.log(exists) // => True if file exists
})
//使用Promise检查路径:
fs.pathExists(file)
.then(exists => console.log(exists)) // => True if file exists
//使用async/await检查路径:
async function pathExistsExample (f) {
const exists = await fs.pathExists(f)
console.log(exists) // => True if file exists
}
pathExistsExample(file)输出
C:\Users\nhooo\> node pathExists.js null true true true
简介ensureSymlinkSync()
此方法还确保符号链接存在。如果不存在,则创建目录结构。
语法
pathExistsSync(file)
参数
file-这是需要在所有文件系统中检查的文件的路径。
例子
在继续之前检查fs-extra是否已安装;如果没有,请安装fs-exra。
您可以使用以下命令来检查是否安装了fs-extra。
npm ls fs-extra
创建一个pathExistsSyncExample.js并将以下代码片段复制粘贴到该文件中。
现在,运行以下命令来运行以下代码片段。
node pathExistsSyncExample.js
代码片段
const fs = require('fs-extra')
const file = '/tmp/dest2/file.txt'
const exists = fs.pathExistsSync(file)
console.log(exists)输出
C:\Users\nhooo\> node createSymlinkSyncExample.js true