Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

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

Background(背景)

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.(我正在对Node.js进行一些实验,并希望从文本文件或.js文件(更好的??)中读取JSON对象到内存中,以便我可以从代码中快速访问该对象。)

I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.(我意识到那里有Mongo,Alfred等东西,但这不是我现在所需要的。)

Question(题)

How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?(如何使用JavaScript / Node从文本或js文件和服务器内存中读取JSON对象?)

  ask by Matt Cashatt translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sync:(同步:)

var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));

Async:(异步:)

var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...