使用 node.js 处理相对路径 [英] Dealing with Relative Paths with node.js
问题描述
我想在我的 node.js 项目中包含一个用于 sqlite3 的 .db
数据库文件.当不同目录中的文件需要打开数据库连接的模块时,我的问题就出现了.
I'm wanting to include a .db
database file for use with sqlite3 in my node.js project. My problem arises when the module which opens the database connection is required by files in different directories.
我的项目结构是这样的:
My project structure is like so:
project/
|--lib/
| |--foo.js
| `--bar.js
|--db/
| `--database.db
`--server.js
我的 foo.js
文件包含打开数据库,如下所示:
My foo.js
file contains opens the database like so:
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('db/database.db');
module.exports = {
foo: function() {
db.serialize(function() { /* Do database things */ });
}
};
当 server.js
文件需要 foo.js
时,这一切正常,如下所示:
This all works fine when foo.js
is required from the server.js
file like so:
var foo = require('./lib/foo');
但是在 lib
目录中的文件 bar.js
需要时它不起作用.
But it doesn't work when required from the file inside the lib
directory, bar.js
.
var foo = require('./foo');
我认为这是因为当这个文件从 lib
目录启动时,.db
文件实际上应该是 ../db/database.db代码>.
I assume this is because when this file is initiated from the lib
directory then the .db
file should actually be ../db/database.db
.
我该如何解决这个问题,我该怎么办?
How can I get around this, what should I do?
推荐答案
当前目录的概念在不同脚本中使用sqlite3.Database
函数时有所不同.它按照 sqlite3 这一行中的设计工作源代码.
the concept current directory differs when using sqlite3.Database
function in different scripts. it works as designed in this line of sqlite3 source code.
所以每次使用时都应该明确指定当前目录.根据你的项目布局,lib/foo.js
中数据库文件的正确路径是
So you should explicitly specify the current directory every time you use it. According to your project layout, the correct path to database file in lib/foo.js
is
var path = require('path')
// specify current directory explicitly
var db = new sqlite3.Database(path.join(__dirname, '..', 'db', 'database.db'));
那么它在任何需要 foo.js
的地方都能工作.
Then it works no matter where it requires foo.js
.
这篇关于使用 node.js 处理相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!