简体   繁体   English

导入JSON内部NPM模块

[英]Import JSON inside NPM Module

I made an npm module , this module export a function that load a json file and then export the result ( a little bit simplified )我做了一个npm module ,这个模块导出一个 function 加载一个json文件然后导出结果(有点简化)

The probleme is when I import this module inside another project I have this error:问题是当我在另一个项目中导入这个module时出现这个错误:

 no such file or directory, open 'C:\Users\{my_username}\github\{name_of_the_project}\file.json'

I looks like when I import my module, it try to read the json inside the current directory and not inside the npm module .我看起来当我导入我的模块时,它尝试读取当前目录中的json而不是npm module中的。

The code inside my module:我的模块内的代码:

export default function() {
    return readFile('./swagger.json')
        .then(data => JSON.parse(data))
}

Final answer (for ES Module):最终答案(对于 ES 模块):

import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import path from 'path';

export default function() {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);

    return readFile(`${__dirname}/swagger.json`)
        .then(data => JSON.parse(data))
}

If you don't use ES Module (but commonJS), __dirname already exist so you can do:如果您不使用 ES 模块(但 commonJS), __dirname已经存在,因此您可以执行以下操作:

export default function() {
        return readFile(`${__dirname}/swagger.json`)
            .then(data => JSON.parse(data))
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM