Windows中带有正斜杠的Nodejs绝对路径 [英] Nodejs absolute paths in windows with forward slash

查看:65
本文介绍了Windows中带有正斜杠的Nodejs绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆