![](/img/trans.png)
[英]Remove context variable in Node.js app before sending to IBM Watson Assistant
[英]Watson Assistant context is not updated
我用的是 watson assistant v1
我的问题是,每次我调用 Nodejs 中的代码,返回上下文,进行协调对话时,上下文只更新一次,我陷入对话的一个节点
这是我的代码
client.on('message', message => {
//general variables
var carpetaIndividual = <../../../>
var cuerpoMensaje = <....>
var emisorMensaje = <....>
//detect if context exists
if(fs.existsSync(carpetaIndividual+'/contexto.json')) {
var watsonContexto = require(carpetaIndividual+'/contexto.json');
var variableContexto = watsonContexto;
} else {
var variableContexto = {}
}
//conection with Watson Assistant
assistant.message(
{
input: { text: cuerpoMensaje },
workspaceId: '<>',
context: variableContexto,
})
.then(response => {
let messageWatson = response.result.output.text[0];
let contextoWatson = response.result.context;
console.log('Chatbot: ' + messageWatson);
//Save and create JSON file for context
fs.writeFile(carpetaIndividual+'/contexto.json', JSON.stringify(contextoWatson), 'utf8', function (err) {
if (err) {
console.error(err);
}
});
//Send messages to my application
client.sendMessage(emisorMensaje, messageWatson)
})
.catch(err => {
console.log(err);
});
}
client.initialize();
context.json 文件已更新,但读取时代码仅读取 context.json 文件的第一个更新,而不是其他更新
这是因为您正在使用require
来读取 .json 文件。 对于一个已经需要的文件的所有后续require
s,数据被缓存和重用。
您将需要使用fs.readfile
和JSON.parse
// detect if context exists
if (fs.existsSync(carpetaIndividual+'/contexto.json')) {
var watsonContexto = fs.readFileSync(carpetaIndividual+'/contexto.json');
// Converting to JSON
var variableContexto = JSON.parse(watsonContexto);
} else {
var variableContexto = {}
}
您的代码还有另一个微妙的问题,因为您依赖于对fs.writeFile
的异步调用在读取文件之前完成。 大多数情况下都是这种情况,但由于您不等待fs.writeFile
完成,因此您可能会在写入文件之前尝试读取该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.