Windows中带有正斜杠的Nodejs绝对路径 [英] Nodejs absolute paths in windows with forward slash
问题描述
我可以在 nodejs 的窗口中使用带正斜杠的绝对路径吗?我正在使用这样的东西:
global.__base = __dirname + '/';var Article = require(__base + 'app/models/article');
但是在 Windows 上构建失败,因为它需要像 C:\Something\Something/apps/models/article
这样的东西.我正在使用 webpack.那么如何规避这个问题,以便要求保持不变,即 __base + 'app/models/src'
?
我知道现在回答有点晚了,但我认为我的回答会对一些访问者有所帮助.
在 Node.js
中,您只需分别使用 __filename
和 __dirname
变量即可轻松获取当前运行的文件名及其目录.
为了根据您的系统更正正斜杠和反斜杠,您可以使用 Node.js
path
模块var path = require('path');
就像这里是一个混乱的路径,如果我想在我的服务器上使用它,我希望它是正确的.这里 path
模块为你做一切
var randomPath = "桌面//我的文件夹/\myfile.txt";
var CorrectPath = path.normalize(randomPath);//就是这样控制台日志(更正路径);
<块引用>
桌面/我的文件夹/myfile.txt
如果你想要一个文件的绝对路径,那么你也可以使用path
模块的resolve
函数
var somePath = "./img.jpg";var resolvePath = path.resolve(somePath);console.log(resolvedPath);
<块引用>
/Users/vikasbansal/Desktop/temp/img.jpg
Can I have absolute paths with forward slashes in windows in nodejs? I am using something like this :
global.__base = __dirname + '/';
var Article = require(__base + 'app/models/article');
But on windows the build is failing as it is requiring something like C:\Something\Something/apps/models/article
. I aam using webpack. So how to circumvent this issue so that the requiring remains the same i.e. __base + 'app/models/src'
?
I know it is a bit late to answer but I think my answer will help some visitors.
In Node.js
you can easily get your current running file name and its directory by just using __filename
and __dirname
variables respectively.
In order to correct the forward and back slash accordingly to your system you can use path
module of Node.js
var path = require('path');
Like here is a messed path and I want it to be correct if I want to use it on my server. Here the path
module do everything for you
var randomPath = "desktop//my folder/\myfile.txt";
var correctedPath = path.normalize(randomPath); //that's that
console.log(correctedPath);
desktop/my folder/myfile.txt
If you want the absolute path of a file then you can also use resolve
function of path
module
var somePath = "./img.jpg";
var resolvedPath = path.resolve(somePath);
console.log(resolvedPath);
/Users/vikasbansal/Desktop/temp/img.jpg
这篇关于Windows中带有正斜杠的Nodejs绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!