node.js和SQLLite的路径问题

时间:2018-12-05 14:15:15

标签: node.js

我有以下代码(缩短了一点)

dbInterface.js

const sqlConnection = require('sqlite3').verbose()
const data = require('./data.js')
//open database --> uses create/readwrite per default
let db = new sqlConnection.Database('./db/test_db.db', (err) => {
  if (err) {
    console.error('Error connecting to database')
  }
  console.log('Connected to the chinook database.')
})

exports.dbFunctions = {
  userPresent: userPresent,
  createTable: createTable,
  tablePresent: tablePresent,
  dropTable: dropTable,
  dropAll: dropTable,
  addUser: addUser,
  deleteUser: deleteUser,
  showTableContent: showTableContent,
  addHistory: addHistory,
  clearHistory: clearHistory,
  removeLastHistoryEntry: removeLastHistoryEntry,
  getHistory: getHistory
}

function userPresent (id) {
  // noinspection SqlResolve
  const statement = 'SELECT * FROM user WHERE pk_user_id == ' + id
  return new Promise((resolve, reject) => {
    db.all(statement, (err, row) => {
      if (err) {
        console.log('reject')
        reject(false)
        return
      }
      console.log('resolve')
      resolve(true)
    })
  })
}

当我在同一文件夹级别访问导出的功能时,一切正常。

我从另一个级别(例如/tests/db_tests.js

调用函数)

例如,我可以使用userPresent,但数据库无法建立连接,除非将其更改为:

let db = new sqlConnection.Database('../db/test_db.db', (err) => {
  if (err) {
    console.error('Error connecting to database')
  }
  console.log('Connected to the chinook database.')
})

看到我将路径位置从./db/test_db.db更改为../db/test_db.db

由于我的应用程序从许多不同的位置访问dbInterface,所以我非常想解决此问题。

我也尝试过使用index.js级别的dbInterface.js并仅包含此内容

exports.dbInterface = require('./dbInterface')

但这也不起作用。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

尝试绝对路径

const path = require('path');
let dbPath = path.join(process.cwd(), 'db', 'test_db.db');