I made an npm module
, this module export a function that load a json
file and then export the result ( a little bit simplified )
The probleme is when I import this module
inside another project I have this error:
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
.
The code inside my module:
export default function() {
return readFile('./swagger.json')
.then(data => JSON.parse(data))
}
Final answer (for ES Module):
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:
export default function() {
return readFile(`${__dirname}/swagger.json`)
.then(data => JSON.parse(data))
}
I think this topic may help you fix your issue
best of luck,,,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.