获取相对于process.cwd()的绝对路径

Oti*_*ght 2 process relative-path absolute-path node.js

我有以下代码块:

#!/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');
});
Run Code Online (Sandbox Code Playgroud)

这需要该位置的绝对路径clone

显然,我现在已经对其进行了硬编码以进行测试,但我想做的是/tmp/获取process.cwd().

所以,我想要的是,如果我运行脚本/home/otis ../../../../tmp/${dirName}会变成../../tmp/${dirName},所以我需要根据process.cwd()

有任何想法吗?

Avr*_*dis 6

您可以使用path.resolve来获取绝对路径。

例如

path.resolve('../src/tmp')
// '/Users/yourusername/src/tmp'
Run Code Online (Sandbox Code Playgroud)

或者您可以使用给出和path.relative( from, to )之间的相对路径fromto

所以就你的情况而言,我想是

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