如何用node找出文件的绝对地址

1,991 阅读1分钟

条件:支持使用node并正确引入fs,path

1、引入fs、path

const fs = require('fs')
const path = require('path')

2、path.resolve([...paths]):根据相对路径获取目标文件的绝对路径

const menuPath = path.resolve('../src/menu')

3、fs.readdirSync(path[, options]):读取目标文件下的所有文件名

const files = fs.readdirSync(menuPath) 

4、path.join([...paths]): 将所有给定的 path 片段连接在一起,以获取每个文件绝对路径

for (let filePath of files) {
    if (filePath.includes('index')) {
      continue
    } else {
      const p = path.join(menuPath, filePath)
    }
  }

(初衷)在项目当中很多时候需要在指定文件中添加共同代码,如果(文件多)手动添加耗时耗力,通过使用node写个小工具添加,不但省时省力还不容易漏