21

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

0

5 Answers 5

34
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');
Sign up to request clarification or add additional context in comments.

5 Comments

this is the same as require('./config.json')
this was related to node.js versions lower than v0.5.x stackoverflow.com/questions/7163061/…
fs.readFile() is not the same as require(). If you try to read the file twice with fs.readFile(), you will get two different pointers in memory. But if you require() with the same string, you will be pointing to the same object in memory, due to caching behavior of required(). This can lead to unexpected results: when modifying the object referenced by the first pointer unexpectedly changes the object modified by the second pointer.
@Blowsie this isn't same as require. require will throw error on dynamically generated file
require will load all huge files in memory when app starts, even if they are never called or needed for a time period.
30

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.

1 Comment

Note that for local files, you need the preceding dot/slash appended to the require ./
15

This one worked for me. Using fs module:

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

1 Comment

I am using exactly this and getting if(err) { throw err; } SyntaxError: Unexpected token }
1

Using import, resolve, toString():

import fs from "fs";
import path from "path";

const boxes_path = path.resolve(__dirname, "boxes.json");
const rawdata = fs.readFileSync(boxes_path);
let data = JSON.parse(rawdata.toString());

Comments

0

comparison of sync vs async :

Sync :
Output : file1 -> file2 -> file3
In this file1 is read then it goes to next file does not matter if the file2 size is less than file1. Given file is read in given order.

Aysnc :
file3 is smaller than file1 and file1 is smaller than file2
Output : file3 -> file1 -> file2
In this according to execution time the file is read. For example If the file3 is of less size then file3 will be executed quickly so, its data is available first and likewise the execution will continue.

asynchronous way to read json file :

import fs from "fs";
import path from "path";

//async way to read json file
fs.readFile('demo.json', function(err, data){
    if(err)throw err;
    // Display the file data
    console.log(JSON.parse(data));
});

synchronous way to read :

let jsonObjData;

try {
  const jsonStringData = fs.readFileSync("./demo.json");
  //convert json string data to json object data
  jsonObjData = JSON.parse(jsonStringData);
} catch (err) {
  console.log(err);
}

//Display json data
console.log(jsonObjData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.