Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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

like image 424
PCA Avatar asked Oct 03 '12 06:10

PCA


People also ask

How do I view a JSON file in node JS?

To load the data from customer. json file, we will use fs. readFile , passing it the path to our file, an optional encoding type, and a callback to receive the file data. If the file is successfully read, the contents will be passed to the callback.


2 Answers

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');
like image 178
Brankodd Avatar answered Sep 19 '22 11:09

Brankodd


Do something like this in your controller.

To get the json file's content :

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

ES6 import foo from './path/to/your/file.json';

To send the json to your view:

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

This should send the json content to your view via a request.

NOTE

According to 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.

like image 20
CENT1PEDE Avatar answered Sep 20 '22 11:09

CENT1PEDE