helper.js
我通常用Ruby编程。我想得到这个信息:
var shopInfo =
{
"shopName": "The Coffee Connection",
"address": "123 Lakeside Way",
"phone": "16503600708",
"prices":
{
"Cafe Latte": 4.75,
"Flat White": 4.75,
"Cappucino": 3.85,
"Single Espresso": 2.05,
"Double Espresso": 3.75,
"Americano": 3.75,
"Cortado": 4.55,
"Tea": 3.65,
"Choc Mudcake": 6.40,
"Choc Mousse": 8.20,
"Affogato": 14.80,
"Tiramisu": 11.40,
"Blueberry Muffin": 4.05,
"Chocolate Chip Muffin": 4.05,
"Muffin Of The Day": 4.55
}
}
}
我想在文件夹中的另一个文件中使用它,因为我希望看起来整洁
main.js
我试过这个:
var helper = require('./helper');
我只想让main.js知道shopInfo是什么
答案 0 :(得分:3)
假设您正在讨论服务器端node.js程序,您可以将其放在另一个模块文件中,然后通过分配到modules.exports
将其导出。
在helper.js中:
var localShopInfo = {
"shopName": "The Coffee Connection",
"address": "123 Lakeside Way",
"phone": "16503600708",
"prices": {
"Cafe Latte": 4.75,
"Flat White": 4.75,
"Cappucino": 3.85,
"Single Espresso": 2.05,
"Double Espresso": 3.75,
"Americano": 3.75,
"Cortado": 4.55,
"Tea": 3.65,
"Choc Mudcake": 6.40,
"Choc Mousse": 8.20,
"Affogato": 14.80,
"Tiramisu": 11.40,
"Blueberry Muffin": 4.05,
"Chocolate Chip Muffin": 4.05,
"Muffin Of The Day": 4.55
}
};
// assign to module.exports to make it available to other modules
module.exports = localShopInfo;
然后,在main.js中:
var shopInfo = require('./helper');
您现在可以在main.js中随意使用shopInfo
。
require()
加载器在其加载的模块中返回module.exports
的值。然后,将其分配给当前模块中要调用它的任何变量。
注意:您的shopInfo
声明中还有一个额外的结束括号。