1 回答
TA贡献1966条经验 获得超4个赞
我看到的是你的应用程序完全不同步 - 我的意思是
你有saveImageToDisk(imageurl,filepath)它将文件写入磁盘,但它执行,将文件写入队列,aa,然后你用同步读取(尚未保存)文件。
我将尝试对它进行一些修复,以向您展示至少一种执行此操作的方法 - 但在规划应用程序的流程时,您需要考虑代码中的一些同步。
console.log('Authenticating bot...');
const {Client, MessageAttachment} = require('discord.js');
const bot = new Client();
const tf = require('@tensorflow/tfjs-node');
const ts = require('@tensorflow/tfjs-core');
require('@tensorflow/tfjs-backend-cpu');
require('@tensorflow/tfjs-backend-webgl');
const coco = require('@tensorflow-models/coco-ssd');
const fs = require('fs');
const fetch = require("node-fetch");
const https = require('https');
const request = require('request');
bot.login('BOTTOKEN');
bot.on('ready', readyDiscord);
function readyDiscord() {
console.log('Authenticated and On!');
}
bot.on('message', gotMessage);
async function gotMessage(msg) {
if(msg.content === '!object') {
const attachments = (msg.attachments).array();
const filepath = "./images/" + Date.now() + "J" + ".jpg";
console.log(filepath);
const imageurl = attachments[0].url;
await saveImageToDisk(imageurl,filepath)
const img_buffer = fs.readFileSync(filepath)
const img = tf.node.decodeImage(img_buffer)
coco.load().then(model => {
// detect objects in the image.
model.detect(img).then(predictions => {
console.log('Predictions: ', predictions);
});
});
msg.reply('Enjoy');
msg.channel.send(attachments[0].url);
}
}
async function saveImageToDisk(url,path) {
return new Promise((resolve, reject) => {
var fullUrl = url;
var localPath = fs.createWriteStream(path);
var request = https.get(fullUrl,function(response) {
console.log(response)
response.pipe(localPath)
response.on('end', resolve);
}).on('error', reject);
});
}
这样,在执行读取尚未填充的文件的代码之前,代码将等待,直到文件被写入(或发生错误) - 您当然应该尝试捕获错误并处理它们。
添加回答
举报