Isaac
Isaac

Reputation: 12874

Relative path with import.meta.url

When working with ESM, quite a number of recommendation to load json file using import.meta.url as below

import fs from 'fs';
const result = fs.readFileSync(
  new URL("abc.json", import.meta.url)
);

Now the above works, but with the assumption that abc.json is in same directory with the location of the script. I'm wondering what about relative path of the script such as abc.json is at one level up of directory. I tried below but it's not working

import fs from "fs";
import path from "path";

const result = fs.readFileSync(
  new URL("abc.json", path.resolve(import.meta.url, "../"))
);

Upvotes: 6

Views: 4487

Answers (1)

Isaac
Isaac

Reputation: 12874

Instead of applying path.resolve to import.meta.url, you should specify the relative path as the first parameter such as below

const result = fs.readFileSync(
  new URL("../abc.json", import.meta.url)
);

Upvotes: 9

Related Questions