我正在定义一个包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在同一目录中。
发布于 2021-08-27 05:10:16
CommonJS模块在其作用域中有__dirname变量,其中包含它们所在目录的路径。
要获得RELATIVE_PATH的绝对路径,请使用join(__dirname, RELATIVE_PATH) (join from path module)。
示例:
// 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,但是你确切地知道PackageA.parseJson是如何被PackageB调用的(比如直接调用,或者通过包装器调用,但是深度是已知的),那么你可以从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)))
}https://stackoverflow.com/questions/68948228
复制相似问题