我正在使用nodejs和microsoft bot框架创建一个机器人,如何从一个单独的文件调用销售数据(我想放入一个单独的文件)而不是放入我的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");
}
}
]);
答案 0 :(得分:1)
对于大多数版本的NodeJ,您只需包含它: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.
./路径/ myJson.json
var familyPerson = {
fname: 'John',
lname: 'Doe',
relationship: 'Son',
....
}
module.exports = familyPerson;
在main.js中,' myjson'现在将包含与familyPerson相同的JSON值。 require语句接受json的路径,相对于调用文件的路径。