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

查看:34
本文介绍了使用 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天全站免登陆