Otis Wright
Otis Wright

Reputation: 2110

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?

Upvotes: 2

Views: 14359

Answers (2)

itereshchenkov
itereshchenkov

Reputation: 247

It's bad practice to use relative paths, especially to system folders. In case if a project location will be changed, you will have to update your code as well. If you need the system temp directory, you can use the following:

require('os').tmpdir()

It will return you correct absolute path to your temporary folder depending on current OS.

Upvotes: 3

Avraam Mavridis
Avraam Mavridis

Reputation: 8920

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/" )

Upvotes: 6

Related Questions