5

I am using a sqlite3 database in my nodejs/express application. I would like to import a .sql file to sqlite when I start up the express server. Since there doesn't appear to be a way to import with the node-sqlite3 package, I'm trying to do it with the exec function.

Both of these commands work when I run them from the command line:

cat db.sql | sqlite3 mydb.db sqlite3 mydb.db < db.sql

However, when I try to run either of these commands via the nodejs exec function, the mydb.db file is created, but it is empty. Here is my code:

var exec = require('child_process').exec;

child = exec('cat db.sql | sqlite3 mydb.db',
    function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
            console.log('exec error: ' + error);
        }
);

When I start my express server I get no output: Express server listening on ip:localhost port:3000 stdout: stderr:

The db file is created, but with a file size of 0. When I open it with sqlite, there are no tables in mydb.db

I tried both ways as shown above and neither of them work. I also tried using spawn and didn't have any success with that, either. How can I import a sql file to a new db within nodejs?

1 Answer 1

1

Pipe | is a shell tool for chaining commands. In Node you need to separate your commands and redirect first output to next input.

var fs = require("fs")
, spawn = require("child_process").spawn
, child = spawn("sqlite3", ["mydb.db"])

fs.createReadStream("./db.sql").pipe(child.stdin)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.