首页 > 解决方案 > 如何访问与 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 位于同一目录中。

标签: javascriptnode.jsjsontypescript

解决方案


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)))
}


推荐阅读