node.jsprocessrelative-pathabsolute-path

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?


Solution

  • 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.