Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Last active May 17, 2021 22:20
Show Gist options
  • Save Avi-E-Koenig/ecd387abfaddb4ef9e26fdce342f525c to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/ecd387abfaddb4ef9e26fdce342f525c to your computer and use it in GitHub Desktop.
async await Sqlite connection with db file write (if not exists)
const sqlite3 = require('sqlite3').verbose();
const { open } = require('sqlite');
const path = require('path');
const fs = require('fs').promises;
async function checkFileExists(file) {
try {
return await fs.stat(file);
} catch (error) {
return false;
}
}
async function dbConn() {
try {
const dbFile = 'main.db';
const dir = path.join(__dirname, '../data');
const dbFilePath = path.join(dir, dbFile);
const fileExists = await checkFileExists(dbFilePath);
if (!fileExists) {
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(dbFilePath, '');
}
const db = await open({
filename: dbFilePath,
driver: sqlite3.Database,
});
return db;
} catch (error) {
throw new Error(error);
}
}
module.exports = dbConn;
//example use
/*
...
const dbConn = require('./services/db.service');
// Root path
try {
const db = await dbConn();
const query ="SELECT ..."
const result = await db.all(query);
} ...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment