Better-sqlite3: Is there a way with this library to test if a file is a valid SQLite database?

Created on 30 Jul 2020  路  3Comments  路  Source: JoshuaWise/better-sqlite3

Hello. I have a question about whether something is possible to do with this library. Say I have a folder of many files of many different types -- how can I pick out the files which are SQLite databases from files of other types (without relying on file extensions)? Thanks

All 3 comments

const Database = require('better-sqlite3');

function isSqliteDatabase(filepath) {
  try {
    new Database(filepath, { fileMustExist: true });
    return true;
  } catch (err) {
    return false;
  }
}

This should generally work too (without using this library), but may rarely give false positives:

const fs = require('fs');

function isSqliteDatabase(filepath) {
  const file = fs.openSync(filepath);
  try {
    const buf = Buffer.alloc(16);
    fs.readSync(file, buf, 0, 16, 0);
    return buf.toString() === 'SQLite format 3\0';
  } catch (err) {
    return false;
  } finally {
    fs.closeSync(file);
  }
}

https://www.sqlite.org/fileformat.html

Thank you for responding and for the help :+1:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ccpwcn picture ccpwcn  路  4Comments

anlaplante picture anlaplante  路  4Comments

Alon-L picture Alon-L  路  5Comments

mann-david picture mann-david  路  5Comments

Babalon921 picture Babalon921  路  3Comments