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 :
JavaScript
x
2
1
no such file or directory, open 'C:Users{my_username}github{name_of_the_project}file.json'
2
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 :
JavaScript
1
5
1
export default function() {
2
return readFile('./swagger.json')
3
.then(data => JSON.parse(data))
4
}
5
Advertisement
Answer
Final answer (for ES Module) :
JavaScript
1
12
12
1
import { readFile } from 'fs/promises';
2
import { fileURLToPath } from 'url';
3
import path from 'path';
4
5
export default function() {
6
const __filename = fileURLToPath(import.meta.url);
7
const __dirname = path.dirname(__filename);
8
9
return readFile(`${__dirname}/swagger.json`)
10
.then(data => JSON.parse(data))
11
}
12
If you don’t use ES Module (but commonJS), __dirname
already exist so you can do :
JavaScript
1
5
1
export default function() {
2
return readFile(`${__dirname}/swagger.json`)
3
.then(data => JSON.parse(data))
4
}
5