Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import PostgreSQL database dump via node and pg

I'm trying to import a PostgreSQL database dump, saved as a plain text file, into psql using the pg package in node.

so far I'm reading in the file as a string, then attempting to import the string via the following method:

var sql = fs.readFileSync('./dbDumpOutput').toString();
pg.connect('postgres://localhost:5432/testdb', function(err, client, done){
    if(err){
        console.log('error: ', err);
        process.exit(1);
    }
    client.query(sql, function(err, result){
    done();
    if(err){
        console.log('error: ', err);
        process.exit(1);
    }
    process.exit(0);
});

I'm getting the following error: error: { error: syntax error at or near "\"

Is this a formatting issue with my dbdump that I'll have to parse out, or am I doing something else incorrectly?

like image 627
Charlie Griffin Avatar asked Oct 29 '22 06:10

Charlie Griffin


1 Answers

I got a working solution which I've provided below, using psql instead of pg.

const { spawn } = require('child_process');

const child = spawn('createdb', ['psqltest']);

child.on('exit', function (code, signal) {
  console.log('child process exited with ' +
              `code ${code} and signal ${signal}`);
  const cat = spawn('cat',['dbDumpOutput']);
  const imp = spawn('psql',['psqltest']);
  cat.stdout.pipe(imp.stdin);
});
like image 61
Charlie Griffin Avatar answered Nov 15 '22 06:11

Charlie Griffin