Spawn a mysql process to import a database using node

妖精的绣舞 提交于 2020-01-11 11:28:46

问题


I'm trying to write a node script to automatically import a .sql file. I think I am misunderstanding the way to pass arguments to 'spawn'. Here's what I have:

var spawn    = require('child_process').spawn;
var mysqlimport = spawn('/usr/local/bin/mysql', [
    '-u' + database.user,
    '-p' + database.password,
    '-h' + database.address,
    '--default-character-set=utf8',
    '--comments',
    '<"' + fileName + '"'
]);
mysqlimport
        .stdout
        .pipe(logFile)
        .on('data', function(data) {
           console.log(data); 
        })
        .on('finish', function() {
            console.log('finished')
        })
        .on('error', function(err) {
            console.log(err)
        });
mysqlimport.stderr.on('data', function(data) {
   console.log('stdout: ' + data);
});
mysqlimport.on('close', function(code) {
   console.log('closing code: ' + code);
});

And I'm getting the error

stdout: ERROR 1049 (42000): Unknown database '<"/users/user/dumps/sqlfile.sql"

if I don't use the -B flag when exporting, and specify the database name, changing

'<"' + fileName + '"'

to

databaseName + ' <"' + fileName + '"'

I get this other error:

stdout: ERROR 1102 (42000): Incorrect database name ' theDatabase < "/users/user/dumps/sqlfile.sql"'

I know I must be doing something wrong with specifying the argument, but how to fix it? The node documentation around spawning child processes is confusing to me. Thanks for your help!


回答1:


Thanks Paul F! your solution worked. I removed the last argument from the spawn and added to my code:

mysqlimport.stdin.write( '\\. /Users/user/dumps/' + fileName );
mysqlimport.stdin.end();

So In all it looks like:

var mysqlimport = spawn('/usr/local/bin/mysql', [
    '-u' + database.user,
    '-p' + database.password,
    '-h' + database.address,
    '--default-character-set=utf8',
    '--comments'
]);
mysqlimport.stdin.write( '\\. /Users/user/dumps/' + fileName );
mysqlimport.stdin.end();
mysqlimport
        .stdout
        .pipe(logFile)
        .on('data', function(data) {
           console.log(data); 
        })
        .on('finish', function() {
            console.log('finished')
        })
        .on('error', function(err) {
            console.log(err)
        });


来源:https://stackoverflow.com/questions/34660573/spawn-a-mysql-process-to-import-a-database-using-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!