1

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!

1
  • That should work. I'm doing the exact same thing. When you say "it didn't work", are you getting an error? Commented Dec 8, 2014 at 21:14

2 Answers 2

4

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

2 Comments

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.
I dont know why but it says that err is not defined in the throw err statement
0

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);
});

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.