-2

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))
}
nem0z
  • 1,060
  • 1
  • 4
  • 17
  • Does this answer your question? [What is the difference between \_\_dirname and ./ in node.js?](https://stackoverflow.com/questions/8131344/what-is-the-difference-between-dirname-and-in-node-js) – jabaa Aug 05 '22 at 10:19
  • This is very interesserting and it could solve my probleme but I'm using `ES Module` which doesn't support __dirname – nem0z Aug 05 '22 at 10:22
  • Does this answer your question? [ReferenceError: __dirname is not defined in ES module scope](https://stackoverflow.com/questions/72456535/referenceerror-dirname-is-not-defined-in-es-module-scope) – jabaa Aug 05 '22 at 10:22

1 Answers1

0

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))
    }
nem0z
  • 1,060
  • 1
  • 4
  • 17