使用Node.JS,如何将JSON对象读入(服务器)内存? [英] Using Node.JS, how do I read a JSON object into (server) memory?
本文介绍了使用Node.JS,如何将JSON对象读入(服务器)内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在对Node.js进行一些实验,并希望从文本文件或.js文件中读取JSON对象(这是更好?? ??进入内存,以便我可以从代码中快速访问该对象。我意识到那里有Mongo,Alfred等东西,但这不是我现在所需要的。
I am doing some experimentation with Node.js and would like to read a JSON object, either from a text file or a .js file (which is better??) into memory so that I can access that object quickly from code. I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.
如何使用JavaScript / Node从文本或js文件中读取JSON对象并进入服务器内存?
How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?
推荐答案
同步:
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));
异步:
var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});
这篇关于使用Node.JS,如何将JSON对象读入(服务器)内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文