Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute path relative to process.cwd()

I have the following code block:

#!/usr/bin/env node

const path = require('path');
const yargs = require('yargs').argv;
const ghpages = require('gh-pages');
const randomstring = require("randomstring");

const dirName = randomstring.generate({
  length: 12,
  charset: 'alphabetic'
});

console.log(__dirname, dirName, process.cwd(), yargs.directory, yargs.branch);

ghpages.publish(path.join(process.cwd(), yargs.directory), {
  branch: yargs.branch,
  clone: `../../../../tmp/${dirName}`
}, () => {
  console.log('removing');
});

This requires an absolute path to the clone location.

Obviously, I have hard coded it at the moment for testing, but what I want to do is get the absolute path to /tmp/ from the process.cwd().

So, what I want is if I ran the script in /home/otis ../../../../tmp/${dirName} would become ../../tmp/${dirName}, so I need to generate the path based on the process.cwd()

Any ideas?

like image 709
Otis Wright Avatar asked Nov 27 '25 00:11

Otis Wright


1 Answers

You can use path.resolve to get the absolute path.

e.g.

path.resolve('../src/tmp')
// '/Users/yourusername/src/tmp'

Or you can use the path.relative( from, to ) which gives the relative path between from and to

So in your case, I guess it is

path.relative( process.cwd(), "../../../../tmp/" )

like image 59
Avraam Mavridis Avatar answered Nov 29 '25 18:11

Avraam Mavridis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!