Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
How to get relative path to an imported file in node.js

I have the following file:

import {something} from '../../something';

something.do();

And I want to get something's relative path as a string, but dynamically rather than to write it implicitly. Something like this:

import {something} from '../../something';

getPath(something); // will return '../../something'

something.do();

What are my options? Is it even possible?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can get a relative path to an imported file as follows

FIRST APPROACH: (the imported file is modified):

  1. Assume that you have a test folder. Inside the test folder, you have test1.js and /mod/test2.js files.

test/mod/test2.js

// here are some of your codes

export const importedFilePath = import.meta.url;  // export current file absoulte path
  1. Now inside the test/test1.js file:

path.relative(from, to) method returns the relative path from to to based on the current working directory. If from and to each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.

If a zero-length string is passed as from or to, the current working directory will be used instead of the zero-length strings. Documentation

import path from 'path'
import { importedFilePath } from './mod/test2.js';

const currentFilePath = import.meta.url;

console.log(path.relative(currentFilePath, importedFilePath)); 

Output:

..\mod\test2.js

Now you have the relative path from test/test1.js to test/mod/test2.js

I know this is not a perfect solution but you can achieve the result you want using the above approach.

SECOND APPROACH

If you would be using the CommonJS module system you can be achieved this result without modifying the imported file.

Assume you use the CommonJS module. Without any modification to the imported file you can achieve the same result as above as follows:

test/test1.js file:

const file = require('./mod/test2');
const path = require('path');

const importedFilePath=require.cache[__filename].children[0].id; //this returns imported file path
const currentFilePath = __filename;

console.log(path.relative(currentFilePath, importedFilePath)); 

And output:

..\mod\test2.js
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!