问题
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