简体   繁体   English

在node.js中处理相对路径的标准方法

[英]standard way to deal with relative paths in node.js

Node.js path resolve system make me mad. Node.js路径解析系统让我发疯。 I have var a = '../data/data.db' path to a file but this path resolve differently depending from am I run this code from node.js directly or from test runner or from CI. 我有一个文件的var a = '../data/data.db'路径,但是此路径的解析方式有所不同,具体取决于我是直接从node.js还是从测试运行器或CI运行此代码。 Is there is a standard unified way how relative paths need to be managed in node.js? 有没有一种标准的统一方法,需要如何在node.js中管理相对路径?

You should use the __dirname property and path.resolve . 您应该使用__dirname属性和path.resolve __dirname gives you the path to the scripts location as opposed to the current execution location, and path.resolve cleans up the relative path. __dirname为您提供了脚本位置的路径,而不是当前执行位置,而path.resolve清除了相对路径。

var path = require('path');
var a = path.resolve(__dirname, '../data/data.db');

您可以使用诸如__dirname之类的全局变量,它指向当前正在执行的脚本所在的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM