javascript - 如何访问与 Node 中的调用模块相关的 JSON 文件?
问题描述
我正在定义一个包 PackageA,它有一个函数 (parseJson),它接收到要解析的 json 文件的文件路径。在另一个包 PackageB 中,我希望能够使用我通过 PackageB 的本地路径指定的文件来调用 PackageA。例如,如果 file.json 与 packageB 位于同一目录中,我希望能够调用PackageA.parseJson('./file.json')
,而无需在 PackageB 中添加任何额外代码。我该怎么做?似乎require
需要从 PackageA 到文件的路径,这不是我想要的。
编辑:目前, parseJson 看起来像这样:
public parseJson(filepath) {
let j = require(filepath);
console.log(j);
}
PackageB 是这样称呼它的:
let a = new PackageA();
a.parseJson("./file.json");
file.json 与 PackageB 位于同一目录中。
解决方案
CommonJS 模块__dirname
在其范围内具有变量,包含它们所在目录的路径。
获取RELATIVE_PATH
使用的绝对路径join(__dirname, RELATIVE_PATH)
(join
来自path
模块)。
例子:
// PackageB .js file
const Path = require('path')
const PackageA = require(/* PackageA name or path */)
const PackageB_jsonPathRelative = /* relative path to json file */
// __dirname is directory that contains PackageB .js file
const PackageB_jsonPathAbsolute = Path.join(__dirname, PackageB_jsonPathRelative)
PackageA.parseJson(PackageB_jsonPathAbsolute)
更新
如果您无法更改 PackageB,但您确切知道 PackageB 是如何PackageA.parseJson
调用的(例如直接调用,或通过包装器调用,但深度已知),那么您可以从stack-trace获取到 PackageB 的路径。
例子:
// PackageA .js file
// `npm install stack-trace@0.0.10` if you have `ERR_REQUIRE_ESM` error
const StackTrace = require('stack-trace')
const Path = require('path')
const callerFilename = (skip=0) => StackTrace.get(callerFilename)[skip + 1].getFileName()
module.exports.parseJson = (caller_jsonPathRelative) => {
// we want direct caller of `parseJson` so `skip=0`
// adjust `skip` parameter if caller chain changes
const callerDir = Path.dirname(callerFilename())
// absolute path to json file, from relative to caller file
const jsonPath = Path.join(callerDir, caller_jsonPathRelative)
console.log(jsonPath)
console.log(JSON.parse(require('fs').readFileSync(jsonPath)))
}
推荐阅读
- php - 本地与部署的 Laravel 问题
- javascript - Chrome 以外的浏览器中的 JSON.parse 错误
- python - 在 Python3 中将 unicode 序列转换为字符串,但允许字符串中的路径
- go - 使用 Golang Mux 路由器和 http.FileServer 的预期根文件和自定义 404
- java - 通过字段 'dashboardService' 表达的不满足的依赖关系;预计至少有 1 个 bean 有资格作为 autowire 候选者
- php - MySQLi real_connect 失败
- tensorflow - 是否有任何可以识别数字集群本身的无监督聚类技术?
- php - 如果我有 500 或 1000 个字符,PHPExcel 在一个单元格中的两种颜色不起作用
- ios - Siri 快捷方式:如何为 iOS 快捷方式的意图参数创建 UI?
- python - 合并熊猫 groupBy 对象