[英]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))
}
I think this topic may help you fix your issue我认为这个主题可以帮助您解决问题
https://stackoverflow.com/questions/35048686/whats-the-difference-between-path-resolve-and-path-join#:~:text=Adding%20a%20%2Fpath%20as%20any%20of%20arguments.&text=resolve()%20process%20the%20sequence,with%20root%20and%20produce%20output . https://stackoverflow.com/questions/35048686/whats-the-difference-between-path-resolve-and-path-join#:~:text=Adding%20a%20%2Fpath%20as%20any%20of%20arguments .&text=resolve()%20process%20the%20sequence,with%20root%20and%20produce%20output 。
best of luck,,,祝你好运,,,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.