如何在node.js中为spawn child\u进程提供密码

yfjy0ee7  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(486)

我正在尝试使用mysqldump创建应用程序的mysql备份。生成子进程似乎无法写入密码。这些都是我迄今为止尝试过的东西。

var spawn = require('child_process').spawn("mysqldump",
["-u", "Username", 
"DBName", 
">", "./Backup/DB_Backup.sql", 
"-p", "Password"]);

spawn.stdin.write("P");
spawn.stdin.write("a");
spawn.stdin.write("s");
spawn.stdin.write("s");
spawn.stdin.write("w");
spawn.stdin.write("o"); 
spawn.stdin.write("r");
spawn.stdin.write("d");
spawn.stdin.write("\n");

spawn.stdin.write("Password\n");

spawn.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
    spawn.stdin.write("Password\n");
});

spawn.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
});

spawn.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

这个问题看起来像是重复的,但没有一个答案对我有帮助。

nnsrf1az

nnsrf1az1#

替换 "-p", "Password""-pPassword" 例子:

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

const mysqldump = spawn('mysqldump', [
    '-u', db.user,
    '-p' + db.password,
    db.database
]);
30byixjq

30byixjq2#

最好的方法是:

const DATABASE_NAME = 'test'
        let wstream = fs.createWriteStream(`./backup/${DATABASE_NAME}.sql`);
        let mysqldump = spawn('mysqldump', [
            `--host=${process.env.MYSQL_HOST}`,
            `--port=${process.env.MYSQL_PORT}`,
            `--user=${process.env.MYSQL_USER}`,
            `--password=${process.env.MYSQL_PASSWORD}`,
            DATABASE_NAME
        ])
        mysqldump
            .stdout
            .pipe(wstream)
            .on('finish', function () {
                console.log('Completed')
            })
            .on('error', function (err) {
                console.error(err)
            })

相关问题