如何使用__dirname返回 1 个文件夹级别

How to go back 1 folder level with __dirname?

本文关键字:文件夹 返回 何使用 dirname      更新时间:2023-09-26

我正在使用gulp-karma并面临一个简单的问题,但似乎找不到我做错了什么。

gulp.task('test', function (done) {
    karma.start({
        configFile: __dirname + '..''test''' +''karma.conf.js',
        singleRun: true
    }, done);
});

这是我正在使用的代码,我似乎无法在文件夹目录中返回 1 级。当我执行上述操作时,它只是..'附加到文件夹 direcotry 中,而不会返回 1 级(这是 ..' 的常用用法)。以下是文件夹结构。

parent|
      test|karma.conf.js
      webapirole|gulpfile.js

我的文件夹在 Webapirole 文件夹内。 我想返回 1 个文件夹并进入包含 karma.conf.js 文件的测试文件夹。 谁能让我明白我在这里做错了什么?

我收到的错误

[18:06:32] Starting 'tdd'...
ERROR [config]: File C:'Users'Documents'WebApiRole..'test'karma.conf.js does not exist

TL;DR

使用 path.join(__dirname, '..', 'test', 'karma.conf.js') .防止使用斜杠。

长答案

正如许多答案所指出的那样,使用path模块可能是最好的方法。但是,这里的大多数解决方案都回到了使用斜杠,例如:

path.join(__dirname+'../test/karma.conf.js')

但是,通过这样做,您正在击败使用path的目的。人们使用path来执行操作,而不考虑底层操作系统(Linux,Windows等)。只是为了提供一些见解,您可以直接将路径操作作为字符串操作(如__dirname + '../test/karma.conf.js' .您不这样做是因为Linux使用正斜杠(/),Windows使用反斜杠(')。这使得应用程序在跨操作系统移植时容易出错。

因此,更好的方法是:

path.join(__dirname, '..', 'test', 'karma.conf.js')

当然,回来 - 防止在path.join中使用斜杠,而是分散你的参数。

我正在使用(路径)NPM 进行上述用法......

只需要 js 文件中的路径 npm。然后使用

let reqPath = path.join(__dirname, '../../../');//It goes three folders or directories back from given __dirname.

__dirname只是一个字符串。 您可以使用../遍历文件夹结构和 path.join 以解析路径

path = require('path')
configFile: path.join(__dirname, '../test/karma.conf.js'),

你可以像这样使用 Path

const path = require('path'); 
path.join(__dirname, "../");

如果您将路径作为字符串发送,

configFile: path.join(__dirname+'../test/karma.conf.js'),

这行不通。

相反,您必须使用逗号(加号连接两个字符串)

configFile: path.join(__dirname, '../test/karma.conf.js'),

来自根目录

(path.join(__dirname , 'views' ,'main.html')) -> will return Root:/views/main.html

从根的任何子文件夹

(path.join(__dirname , '../views/main.html')) -> same as above

就像Pranav Totla说的那样,用正斜杠("/")或反斜杠("''")硬编码路径会使应用程序在遇到不同的操作系统时容易出错。

使用内置的"路径"模块来防止错误。

// Import "path"
const path = require('path');
// To go down on the three from index.html:
path.join(__dirname, 'css', 'style.css')
// To go up on the three from style.css:
path.join(__dirname, '..', 'img', 'cat.jpg')
// Three
root/
| |_css/
| |_img/
|
|_index.html

我们可以使用 path 模块从当前目录返回一个级别

例:

path.join(__dirname, '..', 'test', 'conf.js')
__dirname -- present directory
..        -- one level
test      -- folder name
config.js -- file (test folder inside)

尝试在..''之前放置一个''

如果没有它,生成的路径将有一个名为 WebApi... 的文件夹作为其中的一部分。 您可以在错误消息输出的路径中看到这一点。

喜欢这个:

gulp.task('test', function (done) { 
  karma.start({ configFile: __dirname + '''..''test''' +''karma.conf.js', singleRun: true }, done); 
});

您可能还想研究如何使用 npm 中的路径库。 它通过根据需要处理添加和删除额外的路径分隔符,使组合路径变得更加容易。

以下是您需要了解的有关相对文件路径的所有信息:

从/开始返回到根目录并从那里开始

从../向后移动一个目录并从那里开始

从../../向后移动两个目录并从那里开始(依此类推...

要继续前进,只需从第一个子目录开始并继续前进。

无论

任何操作系统如何,这都会将您移回 2 个目录:

import { join, sep } from 'path';
join(__dirname, sep, "..", sep, "..");