es module中使用__dirname

直接使用报错 ReferenceError: __dirname is not defined in ES module scope

  1. import path from 'path'
  2. import { fileURLToPath } from 'url'
  3. // import.meta.url file:///D:/CS/Repositories-self/mini-code/code/leetcode/script.js
  4. // __filename D:\CS\Repositories-self\mini-code\code\leetcode\script.js
  5. const __filename = fileURLToPath(import.meta.url)
  6. // __dirname D:\CS\Repositories-self\mini-code\code\leetcode
  7. const __dirname = path.dirname(__filename)

判断文件或文件夹

同步方法

  1. const fs = require('fs');
  2. var pathName = "E:\image"
  3. var stat = fs.lstatSync(pathName);
  4. console.log('是否是文件:'+stat.isFile()) //是文件吗
  5. console.log('是否是文件夹:'+stat.isDirectory()) //是文件夹吗

异步方法

  1. const fs = require('fs');
  2. var pathName = "E:\image"
  3. fs.stat(pathName, function(err, data){
  4. console.log('是否是文件:'+data.isFile()) //是文件吗
  5. console.log('是否是文件夹:'+data.isDirectory()) //是文件夹吗
  6. });

封装同步判断函数

  1. function isDir(pathStr, base = __dirname) {
  2. pathStr = path.resolve(base, pathStr)
  3. const stat = fs.lstatSync(pathStr)
  4. return stat.isDirectory()
  5. }
  6. function isFile(path) {
  7. const stat = fs.lstatSync(path)
  8. return stat.isFile
  9. }