我需要使用 nodeJS 运行一个 shell 脚本文件,该文件执行一组 Cassandra DB 命令。谁能帮我解决这个问题。
db.sh 文件内:
create keyspace dummy with replication = {'class':'SimpleStrategy','replication_factor':3}
create table dummy (userhandle text, email text primary key , name text,profilepic)
最佳答案
您可以使用 nodejs 的“子进程”模块在 nodejs 中执行任何 shell 命令或脚本。让我举个例子,我在 nodejs 中运行一个 shell 脚本(hi.sh)。
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
在这里,当我运行 nodejs 文件时,它将执行 shell 文件,输出将是:
运行
node node_program.js
输出
Hi There!
您只需在 exec
回调中提及 shell 命令或 shell 脚本即可执行任何脚本。
希望这会有所帮助!快乐编码:)
关于node.js - 如何使用 nodejs 运行 shell 脚本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647778/