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