Jhon Caylog
Jhon Caylog

Reputation: 503

node js , accessing json file or data from a seperate file

I am creating a bot using nodejs and microsoft bot framework , how can I call the sales data from a separate file (I want to put in a separate file) instead on putting in in my app.js i just want to access it from other file. Thanks

var salesData = {
    "west": {
        units: 200,
        total: "$6,000"
    },
    "central": {
        units: 100,
        total: "$3,000"
    },
    "east": {
        units: 300,
        total: "$9,000"
    }
};

bot.dialog('getSalesData', [
    function (session) {
        builder.Prompts.choice(session, "Which region would you like sales for?", salesData); 
    },
    function (session, results) {
        if (results.response) {
            var region = salesData[results.response.entity];
            session.send(`We sold ${region.units} units for a total of ${region.total}.`); 
        } else {
            session.send("OK");
        }
    }
]);

Upvotes: 1

Views: 28

Answers (1)

Cooper Campbell
Cooper Campbell

Reputation: 163

For most versions of NodeJs you can just include it: require('somejson.json'). All you have to do is make sure you export it in the json file: module.exports = myJson. Of course this can be made more elegant using newer version of Node.

Example:

main.js;

var myJson = require('./path/myJson.json');
// myJson will now contain the json in the file.

./path/myJson.json

var familyPerson = {
  fname: 'John',
  lname: 'Doe',
  relationship: 'Son',
  ....
}
module.exports = familyPerson;

In main.js, 'myjson' will now contain the same JSON values as familyPerson. the require statement takes in the path to the json, relative to the path of the calling file.

Upvotes: 1

Related Questions