远程 fs.readFile 有问题? (在本地工作但不在服务器上工作)
problem with fs.readFile on remote? (works locally but not on server)
下面的代码适用于 Discord 机器人的随机报价生成器,为了便于阅读,已将其剥离,我遇到的问题是在我的 'dev machine'(enthusiast/hobbyist 顺便说一句)上代码有效真的很好,但是当上传到我的 Droplet(ubuntu 18.04,节点 v8.15)时它什么也没做,甚至没有错误 returned.
const fs = require("fs");
exports.run = async (client, message, args) => {
if (!args || args.length > 0) return message.reply("No need for multiple inputs");
fs.readFile("./quotes.json", "utf8", function(err, data) {
const obj = JSON.parse(data);
const result = obj[Math.floor(Math.random() * obj.length)];
message.channel.send(result.quote);
});
};
当代码在 droplet 上时,我删除了 fs.readfile 和 JSON.parse 块并将回复硬编码到 message.channel.send("it works")
中,它 return 将消息作为预计,我会很感激有人关注事物并建议它是代码问题还是可能是服务器配置问题。
下面的工作代码
tbh,我仍然不知道问题出在哪里,所以我在不到 10 分钟的时间内将其全部重写到一个新文件中。除了添加 __dirname +
fs.readFile(__dirname + "/maiq-quotes.json", "utf8", function(err, data) {
const quotesobj = JSON.parse(data);
var quote = quotesobj[Math.floor(Math.random() * quotesobj.length)];
console.log(quote);
message.channel.send(quote.quote);
});
没有错误有点奇怪,但是仔细检查文件是否在正确的位置(如果找不到它应该抛出错误)并检查权限文件 ls -l
。
你可能想做:
fs.readFile("./quotes.json", "utf8", function(err, data) {
if(err) console.log(err);
以便它向您显示错误
下面的代码适用于 Discord 机器人的随机报价生成器,为了便于阅读,已将其剥离,我遇到的问题是在我的 'dev machine'(enthusiast/hobbyist 顺便说一句)上代码有效真的很好,但是当上传到我的 Droplet(ubuntu 18.04,节点 v8.15)时它什么也没做,甚至没有错误 returned.
const fs = require("fs");
exports.run = async (client, message, args) => {
if (!args || args.length > 0) return message.reply("No need for multiple inputs");
fs.readFile("./quotes.json", "utf8", function(err, data) {
const obj = JSON.parse(data);
const result = obj[Math.floor(Math.random() * obj.length)];
message.channel.send(result.quote);
});
};
当代码在 droplet 上时,我删除了 fs.readfile 和 JSON.parse 块并将回复硬编码到 message.channel.send("it works")
中,它 return 将消息作为预计,我会很感激有人关注事物并建议它是代码问题还是可能是服务器配置问题。
下面的工作代码
tbh,我仍然不知道问题出在哪里,所以我在不到 10 分钟的时间内将其全部重写到一个新文件中。除了添加 __dirname +
fs.readFile(__dirname + "/maiq-quotes.json", "utf8", function(err, data) {
const quotesobj = JSON.parse(data);
var quote = quotesobj[Math.floor(Math.random() * quotesobj.length)];
console.log(quote);
message.channel.send(quote.quote);
});
没有错误有点奇怪,但是仔细检查文件是否在正确的位置(如果找不到它应该抛出错误)并检查权限文件 ls -l
。
你可能想做:
fs.readFile("./quotes.json", "utf8", function(err, data) {
if(err) console.log(err);
以便它向您显示错误