使用 Node.JS,如何将 JSON 对象读入(服务器)内存?

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. I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.

Question

How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?

转载于:https://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-object-into-server-memory

weixin_41568184
叼花硬汉 what do you call server memory ? your nodejs script will work as long as you make it work , but you'll have to store datas somewhere unless you make the nodejs script persistant.
8 年多之前 回复

7个回答

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);
});
weixin_41568174
from.. JSON.parse is synchronous. require just does a whole lot more than JSON.parse. JSON.parse is just parsing JSON. require is parsing JavaScript. I'm sure you can figure out why the latter is slower.
接近 2 年之前 回复
weixin_41568127
?yb? One more point: this is async, but it isn't streaming. For that, you'll need a library (e.g., Oboe.js). The difference is async won't block your execution thread, but unless you're streaming you'll still see massive spikes in memory consumption (like 450mb of memory to process a 70mb JSON file).
2 年多之前 回复
weixin_41568127
?yb? two points: (1) The synchronous answer should just be let imported = require("file.json"). (2) JSON.parse must be asynchronous, because I used this code to load a 70mb JSON file into memory as an object. It takes milliseconds this way, but if I use require(), it chugs.
2 年多之前 回复
csdnceshi59
ℙℕℤℝ I cant believe it was so difficult to find this simple thing. Every answer I got from google was doing an HTTPRequest or using JQuery or doing it in the browser
3 年多之前 回复
csdnceshi70
笑故挽风 what's wrong with this ? @mihai Async-json-error gist code
接近 4 年之前 回复
csdnceshi62
csdnceshi62 For the sake of completeness. Their exists a npm called jsonfile.
4 年多之前 回复
csdnceshi68
local-host I think JSON.parse is synchronous, its directly from v8, which means even with the Async way, people have to be careful with large JSON files. since it would tie up node.
大约 5 年之前 回复

The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

You can then easily load this in your node.js application using require

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
csdnceshi59
ℙℕℤℝ I didn't know that, thanks!
接近 3 年之前 回复
csdnceshi76
斗士狗 For me this does not work :(
大约 4 年之前 回复
csdnceshi73
喵-见缝插针 "require" is meant to be used to load modules or config file you are using through out the lifespan of your application. does not seem right to use this to load files.
4 年多之前 回复
weixin_41568183
零零乙 Another issue/benefit with such method is the fact that required data is cached unless you specifically delete the cached instance
4 年多之前 回复
csdnceshi64
游.程 It works for me may be your location of test.json would be different from his example. I am using node 5.0
接近 5 年之前 回复
csdnceshi60
℡Wang Yan Just so folks know, and if I remember correctly, require in node runs synchronously. Dive in deep here
接近 6 年之前 回复

https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfile_file_options_callback

var fs = require('fs');  

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});  

// options
fs.readFile('/etc/passwd', 'utf8', callback);

https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfilesync_file_options

You can find all usage of Node.js at the File System docs!
hope this help for you!

Asynchronous is there for a reason! Throws stone at @mihai

Otherwise, here is the code he used with the asynchronous version:

// Declare variables
var fs = require('fs'),
    obj

// Read the file and send to the callback
fs.readFile('path/to/file', handleFile)

// Write the callback function
function handleFile(err, data) {
    if (err) throw err
    obj = JSON.parse(data)
    // You can now play with your datas
}
weixin_41568184
叼花硬汉 It's there for a reason.. unless you want it synchronously.
4 年多之前 回复
csdnceshi69
YaoRaoLov Great :-) I don't like inline callbacks though, it can lead to callback nightmares that I'd rather avoid.
8 年多之前 回复
csdnceshi74
7*4 agreed :), added async as well
8 年多之前 回复

At least in Node v8.9.1, you can just do

var json_data = require('/path/to/local/file.json');

and access all the elements of the JSON object.

weixin_41568110
七度&光 Your answer is woefully incomplete. What that gets you is an object, and it doesn't even bother to implement tostring().
2 年多之前 回复
csdnceshi53
Lotus@ This approach loads file only once. If you will change the file.json after new require (without restarting program) data will be from first load. I do not have source to back this, but I had this in app I am building
2 年多之前 回复

In Node 8 you can use the built-in util.promisify() to asynchronously read a file like this

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })
csdnceshi69
YaoRaoLov If you want to use promises, there's also fs/promises as of Node 10. Note: the API is experimental: nodejs.org/api/fs.html#fs_fs_promises_api
大约 2 年之前 回复
csdnceshi74
7*4 .readFile is already async, if you're looking for the sync version, its name is .readFileSync.
2 年多之前 回复

If you are looking for a complete solution for Async loading a JSON file from Relative Path with Error Handling

  // Global variables
  // Request path module for relative path
    const path = require('path')
  // Request File System Module
   var fs = require('fs');


// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
   console.log("Got a GET request for list of users");

     // Create a relative path URL
    let reqPath = path.join(__dirname, '../mock/users.json');

    //Read JSON from relative path of this file
    fs.readFile(reqPath , 'utf8', function (err, data) {
        //Handle Error
       if(!err) {
         //Handle Success
          console.log("Success"+data);
         // Parse Data to JSON OR
          var jsonObj = JSON.parse(data)
         //Send back as Response
          res.end( data );
        }else {
           //Handle Error
           res.end("Error: "+err )
        }
   });
})

Directory Structure:

enter image description here

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐