I have a problem in getting a .json file in express and displaying in a view. Kindly share your examples.
Asked
Active
Viewed 6.2k times
3 Answers
32
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');
-
13this is the same as `require('./config.json')` – Blowsie Nov 04 '14 at 09:21
-
this was related to node.js versions lower than v0.5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd Mar 16 '16 at 18:29
-
5`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. – steampowered Apr 20 '16 at 03:38
-
@Blowsie this isn't same as `require`. require will throw error on dynamically generated file – master_dodo Aug 11 '17 at 14:09
-
`require` will load all huge files in memory when app starts, even if they are never called or needed for a time period. – Priya Ranjan Singh Aug 09 '21 at 09:46
28
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.
CENT1PEDE
- 7,182
- 9
- 66
- 120
-
1Note that for local files, you need the preceding dot/slash appended to the require `./` – Mark Shust at M.academy Aug 15 '16 at 13:25
14
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);
});
Jordi Vicens
- 616
- 6
- 16
Arbie Samong
- 1,195
- 1
- 14
- 17
-
I am using exactly this and getting `if(err) { throw err; } SyntaxError: Unexpected token }` – Piet Jul 27 '15 at 19:39