将新数据推送到外部JSON文件 [英] Push new data to external JSON file
问题描述
我正在尝试将新对象推送到外部Javascript文档中,但是在提取要写入的JSON文件时遇到了问题。我有一个名为check.json的外部本地文件。
I'm trying to push a new object into an external Javascript document but I am having problems pulling in the JSON file to write to. I have an external, local file called check.json.
如何在节点中正确调用外部json文件?
How do I call the external json file correctly in node?
var newData = JSON.parse(check.json);
newData.check.push({
cheap: $el.text()
});
check.json = JSON.stringify(newData);
推荐答案
您可以使用文件系统对象,以读写文件。具体来说, readFile
和<一个href = https://nodejs.org/api/fs.html#fs_fs_writefile_filename_data_options_callback rel = nofollow> writeFile
方法。
You can use the Filesystem object to read and write to files. Specifically, the readFile
and writeFile
methods.
例如,读取:
fs.readFile('/path/to/my/json.json', function (err, data) {
if (err) throw err;
var newData = JSON.parse(data);
});
也就是说,平面文件不是一种好的格式用于存储数据并像数据库一样被访问。您可能会遇到竞争状况并丢失数据。拥有一个真正的数据库来解决这种情况,您会更好。
That said, flat files are not a good format for storing data and being accessed like a database. You can run into race conditions and lose data. You would be better off with a real database that will take case of that sort of thing for you.
SQLite 为您提供了一个简单的文件(但周围有很多保护措施)。如果您真的想将JSON作为存储格式,则可以查看 couchDB 之类的东西。
SQLite gives you a simple file (but puts lots of protection in around it). If you really wanted JSON as the storage format then you could look at something like couchDB.
这篇关于将新数据推送到外部JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!