path.resolve与文件路径

path.resolve与文件路径

Tags
nodejs
description
nodejs中的文件路径
更新时间
Last updated January 28, 2022
假设项目中有这样一个结构
├── script │ ├── script.js │ └── test.js ├── test │ ├── data.json │ └── test.js
且对应script.js中的代码如下
// /script/script.js const fs = require('fs'); const jsonPath = './test/data.json'; const funcPath = '../test/test'; const func = require(funcPath); fs.readFile(jsonPath, (err, data) => { func(data.toString()); })
我们在目录下执行$ node ./script/script.js 即可看到data.json 中的输出。
 
但是通过观察我们可以发现,同样是test目录下的文件data.jsontest.js 我们需要用两个不同的路径去引用,这是因为require 的文件引用方式是以当前路径为起点,而fs.readFile 却是以node目录为开头,如果我们希望让文件的引用也是给予当前脚本所在位置怎么办呢,这就需要用到我们的path 库了,path 库就是专门用于nodejs下的目录管理
 
我们改写上面的代码
const fs = require('fs'); const path = require('path'); const jsonPath = '../test/data.json'; const funcPath = '../test/test'; const func = require(funcPath); fs.readFile(path.resolve(__dirname, jsonPath), (err, data) => { func(data.toString()); })
path.resolve 可以将参数转化成绝对路径,这样无论在哪里执行node脚本fs读到的文件目录都以一致的。__dirname 是模块作用域中的变量,表示当前模块的目录名也就是当前/script 文件夹的绝对路径,除此之外还有一个常用的模块作用域变量__filename 表示当前模块的文件名称的绝对路径,
__dirname 加上../test/data.json 即可拼出data.json文件的绝对路径了。