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

Node.js Nodejs获取相对于process.cwd()的绝对路径,node.js,process,relative-path,absolute-path,Node.js,Process,Relative Path,Absolute Path,因此,我有以下代码块: #!/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: '

因此,我有以下代码块:

#!/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');
});
这需要到
克隆
位置的绝对路径

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

因此,基本上我想要的是,如果我在
/home/otis
。/../../../../../${dirName}
中运行脚本,它将变成
。/../tmp/${dirName}
,因此我需要基于
进程.cwd()生成路径

有什么想法吗


干杯/

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

e、 g

或者,您可以使用,它给出了
之间的相对路径

所以在你的情况下,我想是的


path.relative(process.cwd(),“../../../../tmp/”
您可以使用
path.resolve
获取绝对路径

e、 g

或者,您可以使用,它给出了
到之间的相对路径

所以在你的情况下,我想是的


path.relative(process.cwd(),“../../../../../tmp/”

使用相对路径是不好的做法,尤其是对系统文件夹。如果项目位置将被更改,您也必须更新代码。 如果需要系统临时目录,可以使用以下目录:

require('os').tmpdir()

它将根据当前操作系统返回到临时文件夹的正确绝对路径。

使用相对路径是错误的做法,尤其是系统文件夹。如果项目位置将被更改,您也必须更新代码。 如果需要系统临时目录,可以使用以下目录:

require('os').tmpdir()

它将根据当前操作系统返回到临时文件夹的正确绝对路径。

您可以从
process中举出一个例子吗。cwd()
/tmp
是系统tmp文件夹。@OtisWright
绝对路径相对
是什么意思?既然你有绝对url(process.cwd已经给出了绝对路径),为什么你需要一个相对url?在我的意思问题上增加了一个例子。你能给出一个来自
process.cwd()的例子吗
/tmp
是系统tmp文件夹。@OtisWright你说的
绝对路径相对是什么意思?既然你有绝对url(process.cwd已经给出了绝对路径),为什么你需要相对url?我的意思是这个问题增加了一个例子。我理解,但是
clone
param需要相对路径,这意味着绝对路径不起作用。然后,正如@AvraamMavridis所建议的,你可以使用
require('path')。relative(process.cwd(),require('os').tmpdir())