Javascript NodeJS - 将相对路径转换为绝对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38829118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:54:45  来源:igfitidea点击:

NodeJS - convert relative path to absolute

javascriptnode.jsrelative-pathabsolute-path

提问by cheziHoyzer

In my File-systemmy working directory is here:

在我的文件系统中,我的工作目录在这里:

C:\temp\a\b\c\d

C:\temp\a\b\c\d

and under b\bb there's file: tmp.txt

在 b\bb 下有文件:tmp.txt

C:\temp\a\b\bb\tmp.txt

C:\temp\a\b\bb\tmp.txt

If I want to go to this file from my working directory, I'll use this path:

如果我想从我的工作目录转到这个文件,我将使用这个路径:

"../../bb/tmp.txt"

In case the file is not exist I want to log the full path and tell the user:
"The file C:\temp\a\b\bb\tmp.txt is not exist".

如果文件不存在,我想记录完整路径并告诉用户:
“文件 C:\temp\a\b\bb\tmp.txt 不存在”

My question:

我的问题:

I need some functionthat convertthe relative path: "../../bb/tmp.txt" to absolute: "C:\temp\a\b\bb\tmp.txt"

我需要一些功能转换的相对路径: “../../bb/tmp.txt”绝对: “C:\ TEMP \ A \ B \ BB \ tmp.txt”

In my code it should be like this:

在我的代码中它应该是这样的:

console.log("The file" + convertToAbs("../../bb/tmp.txt") + " is not exist")

回答by DarkKnight

Use path.resolve

path.resolve

try:

尝试:

resolve = require('path').resolve
resolve('../../bb/tmp.txt')

回答by Vaibhav N Naik

You could also use __dirname and __filename for absolute path.

您还可以使用 __dirname 和 __filename 作为绝对路径。