How do I load a json file in the project to the app.js. I tried
var j = require('./JSON1');
but it didnt work. I want later to use the JSON.stringify function in the app.js and send part of it to the client. Anyone knows how to do it? Thank you!
How do I load a json file in the project to the app.js. I tried
var j = require('./JSON1');
but it didnt work. I want later to use the JSON.stringify function in the app.js and send part of it to the client. Anyone knows how to do it? Thank you!
require is for code, but JSON is pure data. You don't want JSON to be code, as non-javascript environments should be able to parse it. As with any data file, you process it in two steps. First you read in the data, then you parse it.
fs.readFile should let you read the file into a string. And then you can JSON.parse(result) that string to get JSON data.
fs.readFile('./JSON1', function(err, result) {
if (err) { throw err; }
var data = JSON.parse(result);
console.log(data); // parsed JSON data! yay!
});
require actually will happily load a JSON file for you. Not to say that I'd recommend it is general server usage, since it blocks, but for loading config for instance, it's not unreasonable.require is only when you have a module exposed in the included file. What you want is plain file inclusion. For that there is a npm package called fs (filesystem)
Example code:
var fs = require("fs");
var fileToOpen = "./JSON1";
fs.readFile(fileToOpen,function(error,data){
if (error){
console.log("error opening file",error);
}
console.log("contents",data);
});