3

I'm trying to use the sqlite3 module to create an in memory SQLite database and the adm-zip module to save it into a zip file. So far I have been able to create an in memory database and add data to it, but I have been unsuccessful in finding a way to store it in a zip made through adm-zip as it requires either a file, buffer or string.

My question is this: does the sqlite3 module even support storing or saving as a buffer? If it doesn't then what would be an advisable solution for storing temporary files in Node.js when the script is used as both a requirable module and a command line script?

I've included the code I've been using to test with below and a cloneable gist.

main.js

var fs = require('fs'),
    admzip = require('adm-zip'),
    sqlite3 = require('sqlite3').verbose(),
    zip = new admzip(),
    db = new sqlite3.Database('test.sqlite');
    // db = new sqlite3.Database(':memory:');

db.serialize(function() {

    db.run('CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY, name TEXT);');
    db.run('INSERT OR IGNORE INTO test(name) VALUES ("neogeek");');

});

zip.addFile('README.md', '#SQLite3 + ADM-ZIP Test');

// zip.addFile('db.sqlite', db);

db.close();

fs.writeFileSync('test.zip', zip.toBuffer(), 'utf8');

package.json

{
    "private": true,
    "dependencies": {
        "sqlite3": "3.0.2",
        "adm-zip": "0.4.4"
    }
}

https://gist.github.com/neogeek/70c80c7ddaf998bee4bd

4

1 回答 1

2

在继续寻找这个问题的答案时,我偶然发现了 npm 模块temp,并且能够组合出一个可行的解决方案,如下所述。

var fs = require('fs'),
    temp = require('temp').track(),
    admzip = require('adm-zip'),
    sqlite3 = require('sqlite3').verbose(),
    zip = new admzip(),
    tempdb = temp.openSync('db.sqlite'),
    db = new sqlite3.Database(tempdb.path);

db.serialize(function() {

    db.run('CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY, name TEXT);');
    db.run('INSERT OR IGNORE INTO test(name) VALUES ("neogeek");');

});

zip.addFile('README.md', '#SQLite3 + ADM-ZIP Test');

db.close(function () {

    zip.addFile('test.sqlite', fs.readFileSync(tempdb.path));

    fs.writeFileSync('test.zip', zip.toBuffer(), 'utf8');

});

我包含了 temp 模块,并确保激活对使用.track().

temp = require('temp').track(),

然后我创建了一个新文件来存储 sqlite 数据库。

tempdb = temp.openSync('db.sqlite'),

最后,我将 sqlite 文件的写入移动到内存 zip 中,并将最终输出的 zip 文件移动到 sqlite 关闭方法回调中。

db.close(function () {

    zip.addFile('test.sqlite', fs.readFileSync(tempdb.path));

    fs.writeFileSync('test.zip', zip.toBuffer(), 'utf8');

});

https://gist.github.com/neogeek/70c80c7ddaf998bee4bd

于 2014-10-15T00:54:12.770 回答