简体   繁体   English

我想编写一个异步JSON联系人,它将覆盖我的data.json文件的内容

[英]I want to write an Async JSON contacts which will overwrite the content of my data.json file

I have written the file contact.js using jsonfile.writeFile. 我已经使用jsonfile.writeFile编写了文件contact.js

Here's my contact.js code: 这是我的contact.js代码:

var Contact = {}
Contact.saveContacts=function(contacts,done){
var jsonfile = require('jsonfile')
jsonfile.writeFile('data.json',contacts, done, function(err){
done(err)
})
}
module.exports=Contact

Here's test.js 这是test.js

var contacts = [ { name: "John Smith", number: "604-123-9090" } ]
Contact.saveContacts(contacts, function(err) {
console.log('success')
  })

I get the following error: 我收到以下错误:

Error: Contact.saveContacts did not write any data or the written data is incorrect. 错误:Contact.saveContacts未写入任何数据或写入的数据不正确。

How can I solve this? 我该如何解决?

You can write your contact.js like below: 您可以像下面这样编写contact.js:

Contact.saveContacts = function(contacts, done) {
var jsonfile = require('jsonfile');

jsonfile.writeFile('data.json', contacts, done);

} }

And your test.js like you wrote. 和您编写的test.js一样。

I hope I've helped. 希望能对您有所帮助。

Okay I solve the solution like this way.I change the contact.js file like this way. 好的,我以这种方式解决了解决方案,我以这种方式更改了contact.js文件。

 var Contact = {}
 Contact.saveContacts=function(contacts,done){
 var jsonfile = require('jsonfile')
 jsonfile.writeFile('data.json',contacts,function(err){
 done(err)
 })
 }

 module.exports=Contact

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM