gpt4 book ai didi

Nodejs absolute paths in windows with forward slash(带正斜杠的窗口中的NodeJS绝对路径)

转载 作者:bug小助手 更新时间:2023-10-25 19:43:04 32 4
gpt4 key购买 nike



Can I have absolute paths with forward slashes in windows in nodejs? I am using something like this :

在NodeJS的窗口中可以有带正斜杠的绝对路径吗?我使用的是这样的东西:



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'?

但在Windows上,构建失败了,因为它需要C:\Something\Something/apps/Models/文章之类的内容。我是在用webpack。那么,如何绕过这个问题,使需求保持不变,即__base+‘app/Models/src’?


更多回答

nodejs.org/api/path.html

Nodejs.org/api/path.html

@Amadan as I said I doont want to change how I require the module

@Amadan,就像我说的,我不想改变我需要模块的方式

If you don't want to change your code, what do you expect us to do?

如果您不想更改您的代码,您希望我们怎么做?

I was talking about alernative way around global.__base = __dirname + '/';. I am willing to change that as that happens only once in the code

我谈论的是有关全局的警报本机方式。__base=__dirname+‘/’;。我愿意更改这一点,因为这在代码中只发生一次

You are still fixing / as the separator in app/models/article. I don't know whether or not C:\Something\Something/apps/models/article works on Windows (I never develop for it), but path.join(__dirname, 'app', 'models', 'article') does.

您仍在修复/作为应用程序/模型/文章中的分隔符。我不知道C:\Something\Something/app/Models/文章是否可以在Windows上运行(我从来没有为它进行过开发),但路径.Join(__dirname,‘app’,‘Models’,‘文章’)可以。

优秀答案推荐

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.

在Node.js中,您只需分别使用__filename和__dirname变量,即可轻松获得当前运行的文件名及其目录。


In order to correct the forward and back slash accordingly to your system you can use path module of Node.js

为了根据您的系统更正正斜杠和反斜杠,您可以使用Node.js的Path模块


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

这里有一条乱七八糟的路径,如果我想在我的服务器上使用它,我希望它是正确的。在这里,Path模块可以为您执行所有操作



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

如果你想要一个文件的绝对路径,那么你也可以使用Path模块的解析功能


var somePath = "./img.jpg";
var resolvedPath = path.resolve(somePath);

console.log(resolvedPath);


/Users/vikasbansal/Desktop/temp/img.jpg



it's 2020, 5 years from the question was published, but I hope that for somebody my answer will be useful. I've used the replace method, here is my code(express js project):

现在是2020年,距离这个问题发表还有5年的时间,但我希望我的答案对某些人有用。我已经使用了Replace方法,以下是我的代码(Express js项目):



const viewPath = (path.join(__dirname, '../views/')).replace(/\\/g, '/')

exports.articlesList = function(req, res) {
res.sendFile(viewPath + 'articlesList.html');
}


I finally did it like this:

我最终是这样做的:



var slash = require('slash');
var dirname = __dirname;
if (process.platform === 'win32') dirname = slash(dirname);

global.__base = dirname + '/';


And then to require var Article = require(__base + 'app/models/article');. This uses the npm package slash (which replaces backslashes by slashes in paths and handles some more cases)

然后需要var文章=Required(__base+‘app/型号/文章’);。这使用了NPM包的斜杠(它用路径中的斜杠替换反斜杠,并处理更多的情况)



The accepted answer doesn't actually answer the question most people come here for.
If you're looking to normalize all path separators (possibly for string work), here's what you need.

被接受的答案实际上并没有回答大多数人来这里想要的问题。如果您希望标准化所有路径分隔符(可能用于字符串工作),以下是您需要的。


All the code segments have the node.js built-in module path imported to the path variable.
They also have the variable they work from stored in the immutable variable str, unless otherwise specified.

所有代码段都将node.js内置模块路径导入到PATH变量。除非另有说明,否则它们使用的变量也存储在不可变变量str中。


If you have a string, here's a quick one-liner normalize the string to a forward slash (/):

如果您有一个字符串,这里有一个快速的一行程序将该字符串标准化为正斜杠(/):


const answer = path.resolve(str).split(path.sep).join("/");

You can normalize to any other separator by replacing the forward slash (/).

您可以通过替换正斜杠(/)来标准化为任何其他分隔符。


If you want just an array of the parts of the path, use this:

如果只需要路径部分的数组,请使用以下命令:


const answer = path.resolve(str).split(path.sep);

Once you're done with your string work, use this to create a path able to be used:

完成字符串工作后,使用此命令创建一条可以使用的路径:


const answer = path.resolve(str);

From an array, use this:

在数组中,使用以下命令:


// assume the array is stored in constant variable arr
const answer = path.join(...arr);


This is the approach I use, to save some processing:

这是我使用的方法,以节省一些处理:


const path = require('path');

// normalize based on the OS
const normalizePath = (value: string): string {
return path.sep === '\'
? value.replace(/\\/g, '/')
: value;
}

console.log('abc/def'); // leaves as is
console.log('abc\def'); // on windows converts to `abc/def`, otherwise leave as is


I recommend against this, as it is patching node itself, but... well, no changes in how you require things.

我建议不要这样做,因为它是修补节点本身,但.你的要求没有改变



(function() {
"use strict";
var path = require('path');
var oldRequire = require;
require = function(module) {
var fixedModule = path.join.apply(path, module.split(/\/|\\/));
oldRequire(fixedModule);
}
})();


Windows uses \, Linux and mac use / for path prefixes

Windows使用\,Linux和Mac使用/作为路径前缀


For Windows : 'C:\\Results\\user1\\file_23_15_30.xlsx'

对于Windows:‘C:\\Results\\User1\\FILE_23_15_30.xlsx’


For Mac/Linux: /Users/user1/file_23_15_30.xlsx

对于Mac/Linux:/USERS/USER1/FILE_23_15_30.xlsx


If the file has \ - it is windows, use fileSeparator as \, else use /

如果文件有\-它是Windows,请使用fileSeparator作为\,否则使用/


let path=__dirname; // or filePath
fileSeparator=path.includes('\')?"\":"/"
newFilePath = __dirname + fileSeparator + "fileName.csv";


It is already too late but the actual answer is using path.sep or path.join depends on the requirement.

现在已经太晚了,但实际的答案是使用path.sep还是使用path.Join,具体取决于需求。


In Windows directory path will be "" and Linux "/" so the path library will do this work automatically.

在Windows目录中,路径将为“”,而Linux将为“/”,因此路径库将自动执行此工作。


const path = require("path");
const abPath = path.join(__base ,'app','models','article')

OR


const path = require("path");
const abPath = __base + 'app'+ path.sep +'models'+ path.sep +'article';


Use path module

使用路径模块


const path = require("path");
var str = "test\test1 (1).txt";
console.log(str.split(path.sep)) // This is only on Windows

更多回答

@VikasBansat: path.normalize(path.resolve('./')) - is effectively the way you suggest. However this does not resolve the issue under Windows 8 (at least).

@VikasBansat:path.Normize(path.Resolve(‘./’))--实际上就是你建议的方式。然而,这并不能解决Windows 8下的问题(至少)。

This doesn't work, at all. Backslashes remain backslashes.

这根本不管用。反斜杠仍保留反斜杠。

This only works for UNIX systems. For Windows, default path delimiter is backslash

这仅适用于UNIX系统。对于Windows,默认路径分隔符为反斜杠

After testing, this doesn't work on windows. Slashes still remain backward with this. This answer should not be the accepted one, because it doesn't solve the problem for Windows, for which it was asked for.

经过测试,这在Windows上不起作用。在这一点上,斜杠仍然落后。这个答案不应该是被接受的,因为它不能解决Windows的问题,因为它是被要求的。

works nicely for me to insert the forward slashed path into a database

我可以很好地将向前斜线的路径插入数据库

I'd rather recommend using nodejs.org/api/path.html#path_path_sep which is the very purpose of this feature ;) And make it a one-liner!

我宁愿推荐使用nodejs.org/api/path.html#PATH_PATH_SEP,这正是该特性的目的;)并使其成为一行程序!

@Vadorequest Thanks for this! Never heard about path.sep before - it was just what is was looking for!

@VadoREQUEST为此感谢!以前从未听说过path.sep--这正是IS正在寻找的!

Thanks for reminding me this solution exists, I had completely forgotten about it ^^'

谢谢你提醒我这个解决方案的存在,我已经完全忘记了^^‘

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com