Javascript NodeJs writeFile writes";“对象对象”;在txt文件中,而不是在对象的实际元素中
这是我的querydb函数。如您所见,我检查该值是否不等于null,如果为true,则调用writeFile。但在.txt中,它只打印“object”。知道发生了什么吗???写文件签名是:Javascript NodeJs writeFile writes";“对象对象”;在txt文件中,而不是在对象的实际元素中,javascript,node.js,writefile,Javascript,Node.js,Writefile,这是我的querydb函数。如您所见,我检查该值是否不等于null,如果为true,则调用writeFile。但在.txt中,它只打印“object”。知道发生了什么吗???写文件签名是: function querydb(){ cursor = dbConnection.collection("logs").find(queryObj).limit(valueList[1]); /*Either decide here to foreach for file or for conso
function querydb(){
cursor = dbConnection.collection("logs").find(queryObj).limit(valueList[1]);
/*Either decide here to foreach for file or for console OR...*/
cursor.forEach(function(item){
/*Decide here whether to write to file or console*/
if(valueList[0] != null){
fs.writeFile(valueList[0], item, 'utf-8', console.log("finished!!"));
}
if(valueList[0] == null){
console.log(item);
console.log("Done");
}
/*CHECK TO SEE IF THE CURSOR IS EXHAUSTED*/
if(cursor == null){
//now we can close the database
dbConnection.close();
}
}
);
};
因此,您正在写入的数据必须是一个对象。这就是为什么Object Object
被写入文件。尝试反序列化“item”参数,如:
fs.writeFile(file, data[, options], callback)
它只是在对象上调用
.toString()
。您可以使用JSON.stringify()
将对象转储为JSON,或者根据需要编写自己的代码将对象呈现为字符串。我检查了如何使用stringify,但其描述中没有那么详细。你能告诉我如何使用它吗???@Pointy我认为你应该把你的评论作为一个实际的答案。因为对我来说,这是问题的正确答案。不,这不是因为我仍然迷路。有人能告诉我我的程序是如何解决这个问题的吗??
fs.writeFile(valueList[0], JSON.stringify(item), 'utf-8', console.log("finished!!"));