es module中使用__dirname
直接使用报错 ReferenceError: __dirname is not defined in ES module scope
import path from 'path'
import { fileURLToPath } from 'url'
// import.meta.url file:///D:/CS/Repositories-self/mini-code/code/leetcode/script.js
// __filename D:\CS\Repositories-self\mini-code\code\leetcode\script.js
const __filename = fileURLToPath(import.meta.url)
// __dirname D:\CS\Repositories-self\mini-code\code\leetcode
const __dirname = path.dirname(__filename)
判断文件或文件夹
同步方法
const fs = require('fs');
var pathName = "E:\image"
var stat = fs.lstatSync(pathName);
console.log('是否是文件:'+stat.isFile()) //是文件吗
console.log('是否是文件夹:'+stat.isDirectory()) //是文件夹吗
异步方法
const fs = require('fs');
var pathName = "E:\image"
fs.stat(pathName, function(err, data){
console.log('是否是文件:'+data.isFile()) //是文件吗
console.log('是否是文件夹:'+data.isDirectory()) //是文件夹吗
});
封装同步判断函数
function isDir(pathStr, base = __dirname) {
pathStr = path.resolve(base, pathStr)
const stat = fs.lstatSync(pathStr)
return stat.isDirectory()
}
function isFile(path) {
const stat = fs.lstatSync(path)
return stat.isFile
}