node.js - Node js ,访问 json 文件或来自单独文件的数据

标签 node.js

我正在使用nodejs和微软机器人框架创建一个机器人,如何从单独的文件(我想放入单独的文件)中调用销售数据,而不是放入我只想访问的app.js中来自其他文件。谢谢

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

最佳答案

对于大多数版本的 NodeJs,您只需包含它即可:require('somejson.json')。您所要做的就是确保将其导出到 json 文件中:module.exports = myJson。当然,使用新版本的 Node 可以使这变得更加优雅。

示例:

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;

在 main.js 中,“myjson”现在将包含与 familyPerson 相同的 JSON 值。 require 语句接受 json 的路径,相对于调用文件的路径。

关于node.js - Node js ,访问 json 文件或来自单独文件的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292854/

相关文章:

node.js - ExpressJS 中缓存如何工作的说明

node.js - LevelDOWN : NODE_MODULE_VERSION error when testing, 但未运行

javascript - 如何在聚合中从数组中删除数据而不干扰 mongodb 中的外部数据

javascript - 将 HTML/Express.js 设置从 POST 更改为 PUT?

javascript - 类型错误 : Cannot read property 'find' of undefined with mongoose

javascript - morgan 弃用 expressjs

mysql - 如何将MySQL数据库的结果放在Node.js中的变量中?

node.js - Nodejs Redis createClient() 函数

javascript - 为什么我的 JavaScript 会抛出““No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?

javascript - 删除 Node 后使用 escodegen 生成代码时出错