使用exec启动Discord.js bot的Node js无法正常运行
假设我有2个文件,a.js和b.js,其中a.js是一个简单的node.js脚本,它调用了一个Discord.js bot的b.js。
a.js
const { exec } = require('child_process'); exec('node b.js', (err,stdout,stderr) => { console.log('err: ' + err + '\n stdout: ' + stdout + '\n stderr:' + stderr); });
b.js
const Discord = require('discord.js'); const fs = require('fs'); var bot = new Discord.Client(); var token; fs.readFile('token.txt',(err,data) => { if(err){console.log(err); process.exit(0);} token = data; }); bot.on('ready',()=>{console.log('ready');}); bot.on('message', message => { if(message.content == 'ping'){ message.channel.send('pong'); } }); bot.login(token);
当我运行a.js时,唯一的输出是
err: stdout: stderr:
a.js然后终止,并且似乎b.js从未运行。 我想知道为什么发生这种情况,为什么。 另外如果有人想知道为什么我这样做,我把这个作为一个更大的脚本的一部分,我把这个问题解决了。 主要部分是b.js必须从exec运行。 我在Windows 10中使用最新版本的节点和Discord.js来运行此操作。 谢谢
我有另一个去这个,但通过完全不和谐机器人设置…
我的a.js
看起来像这样…
const { spawn } = require('child_process'); const child = spawn('node',['b.js']); process.stdin.pipe(child.stdin); child.stdout.on('data', (data) => { console.log(`child stdout:\n${data}`); }); child.stderr.on('data', (data) => { console.log(`child stderr:\n${data}`); });
我的b.js
看起来像这样
const Discord = require('discord.js'); const fs = require('fs'); var bot = new Discord.Client(); var token; fs.readFile('token.txt', {encoding: 'utf8'}, (err,token) => { if(err){console.log(err); process.exit(0);} bot.on('ready',()=>{ console.log('ready'); }); bot.on('message', message => { if(message.content == 'ping'){ message.channel.send('pong'); } }); bot.login(token); });
在b.js
,我不得不读取文件,并确保我的token.txt
文件没有尾随,领先的空白。 另外,我将botlogin代码移入了读取令牌文件的callback。
下面的输出示例…
我发出不和谐的声音,看是否有效,机器人响应乒乓球。
下面的截图。
我希望这个代码适合你,让我知道…
我用b.js来运行a.js,除了我把b.js改成了console.log
a.js
const { exec } = require('child_process'); exec('node b.js', (err,stdout,stderr) => { console.log('err: ' + err + '\n stdout: ' + stdout + '\n stderr:' + stderr); });
b.js
console.log("B was called");
然后当我运行节点a.js我得到;
node .\a.js err: null stdout: B was called stderr:
我猜测有一个path问题,A无法findB相对于从哪里被调用?