Dealing with Relative Paths with node.js

一笑奈何 提交于 2021-02-18 17:50:08

问题


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

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 */ });
  }
};

This all works fine when foo.js is required from the server.js file like so:

var foo = require('./lib/foo');

But it doesn't work when required from the file inside the lib directory, bar.js.

var foo = require('./foo');

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?


回答1:


the concept current directory differs when using sqlite3.Database function in different scripts. it works as designed in this line of sqlite3 source code.

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'));

Then it works no matter where it requires foo.js.



来源:https://stackoverflow.com/questions/27766734/dealing-with-relative-paths-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!