node.js 如何在express js中获取json文件并在view中显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12703098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:24:26  来源:igfitidea点击:

How to get a json file in express js and display in view

node.js

提问by PCA

I have a problem in getting a .jsonfile in express and displaying in a view. Kindly share your examples.

.json在快速获取文件并在视图中显示时遇到问题。请分享你的例子。

回答by Brankodd

var fs = require("fs"),
    json;

function readJsonFileSync(filepath, encoding){

    if (typeof (encoding) == 'undefined'){
        encoding = 'utf8';
    }
    var file = fs.readFileSync(filepath, encoding);
    return JSON.parse(file);
}

function getConfig(file){

    var filepath = __dirname + '/' + file;
    return readJsonFileSync(filepath);
}

//assume that config.json is in application root

json = getConfig('config.json');

回答by CENT1PEDE

Do something like this in your controller.

在你的控制器中做这样的事情。

To getthe jsonfile's content :

为了获得JSON文件的内容:

ES5var foo = require('./path/to/your/file.json');

ES5var foo = require('./path/to/your/file.json');

ES6import foo from './path/to/your/file.json';

ES6import foo from './path/to/your/file.json';

To sendthe jsonto your view:

发送JSON到您的视图:

function getJson(req, res, next){
    res.send(foo);
}

This should send the jsoncontent to your view via a request.

这应该通过请求将json内容发送到您的视图。

NOTE

笔记

According to BTMPL

根据BTMPL

While this will work, do take note that require calls are cached and will return the same object on each subsequent call. Any change you make to the .json file when the server is running will not be reflected in subsequent responses from the server.

虽然这会起作用,但请注意 require 调用会被缓存,并且会在每次后续调用中返回相同的对象。您在服务器运行时对 .json 文件所做的任何更改都不会反映在服务器的后续响应中。

回答by Arbie Samong

This one worked for me. Using fs module:

这个对我有用。使用 fs 模块:

var fs = require('fs');

function readJSONFile(filename, callback) {
  fs.readFile(filename, function (err, data) {
    if(err) {
      callback(err);
      return;
    }
    try {
      callback(null, JSON.parse(data));
    } catch(exception) {
      callback(exception);
    }
  });
}

Usage:

用法:

readJSONFile('../../data.json', function (err, json) {
  if(err) { throw err; }
  console.log(json);
});

Source

来源