Thursday 24 August 2017

Reference Error - But why?

Hey there currently I'm developing an applications backend as express REST API. I'm using sqlite3 as database and I was about to develop a prestat-script to create all neccessary tables on start.Following code:const path = require('path'); const sqlite3 = require('sqlite3').verbose(); const deasync = require('deasync'); const config = require('../config'); const dbPath = `${path.join(config.dbConfig.path, config.dbConfig.name)}.db`; const db = new sqlite3.Database(dbPath); const get = deasync(db.get); const run = deasync(db.run.bind(db)); function tableExists(table) { try{ get(`SELECT * FROM ${table} LIMIT 1`); return true; } catch(err) { return false; } } function createTable(name, columns) { const tableColumns = columns.map(c => `${c.name} ${c.type}`); run(`CREATE TABLE ${name} (${tableColumns})`); } function ensureTable(name, columns) { console.log(`Ensuring TABLE ${name}`) if (!tableExists(name)) { console.log(`Creating TABLE ${name}`); createTable(name, columns); } else { console.log(`TABLE ${name} already exists.`) } } console.log(`Precheck Database ${dbPath}`); config.dbConfig.tables.forEach(t => ensureTable(t.name, t.columns)); console.log('Database check done.') I'm getting a ReferenceError in the function tableExists - saying Database reference is missing (coming from sqlite3). Through debugging I found that in the function ensureTable my variable db is undefined, outside of any function db is set. Any suggestions on why this error is occuring? I have no clue - googling for any help is especially complicated because you'll find a lot help for ReferenceErrors, but not for this case.dividerEdit: I've checked, this error is not coming from deasync, as db is undefined in ensureTable which is not deasynced. The db variable is instanciated, I can see this while debugging and breaking at e.g. the line "Precheck Database ...". As soon as I'm entering a function it's lost. So maybe theres something about scoping I'm missing here?dividerP.S: I am using node v8.2.0

Submitted August 24, 2017 at 08:15AM by br0wnvetter

No comments:

Post a Comment