使用Node.JS,如何将JSON文件读取到(服务器)内存中? [英] Using Node.JS, how do I read a JSON file into (server) memory?

查看:152
本文介绍了使用Node.JS,如何将JSON文件读取到(服务器)内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对Node.js进行一些试验,希望将JSON对象从文本文件或.js文件(更好的??)读取到内存中,以便可以从代码中快速访问该对象. .我意识到那里有诸如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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆