Alexa lambda JS 如何从外部 .js 文件访问数组数据
Alexa lambda JS how to access array data from external .js file
我正在使用 JS 代码在 lambda 中构建 alexa 技能。
我有 2 个文件。一个具有 alexa 技能正常工作的常规代码,第二个文件有一个数组,其中包含触发 Inttent 时我需要的数据。
我必须使用什么代码才能让 alexa 从第二个文件中读取数组数据?
文件 1
let CountryInfoSlot = resolveCanonical(this.event.request.intent.slots.CountryInfo);
console.log (CountryInfoSlot);
CountryInfoSlot = CountryInfoSlot.toLowerCase();
if (CountryInfoSlot == 'France'){
var FranceInfo = require ('/FranceInfo.js');
var N = FranceInfo.length;
var index = Math.round(Math.random()*(N-1));
var answer = FranceInfo[index];
this.response.speak(answer);
this.emit(':responseReady);
}
文件 2
var FranceInfo = [
'The language spoken in France is french',
'Paris is the capital of France',
];
您可以使用 fs
读取并将值作为数组存储在第二个文件中并在第一个文件中解析。
或
因为您在第一个文件中使用 require
,所以在第二个文件的末尾使用 module.exports = FranceInfo
,以便它可以加载到第一个
您必须更改信息文件才能导出数据。更改文件 2 以导出要访问的变量,如下所示:
var FranceInfo = [
'The language spoken in France is french',
'Paris is the capital of France',
];
module.exports.data = FranceInfo;
然后您可以像这样在第一个文件中要求该变量:
const FranceInfoData = require('./FranceInfo');
var FranceInfo = FranceInfoData.data;
那么您的 FranceInfo 变量将等于外部文件中的数组。
这不是唯一的方法,但它是最简单的方法之一。
我正在使用 JS 代码在 lambda 中构建 alexa 技能。 我有 2 个文件。一个具有 alexa 技能正常工作的常规代码,第二个文件有一个数组,其中包含触发 Inttent 时我需要的数据。
我必须使用什么代码才能让 alexa 从第二个文件中读取数组数据?
文件 1
let CountryInfoSlot = resolveCanonical(this.event.request.intent.slots.CountryInfo);
console.log (CountryInfoSlot);
CountryInfoSlot = CountryInfoSlot.toLowerCase();
if (CountryInfoSlot == 'France'){
var FranceInfo = require ('/FranceInfo.js');
var N = FranceInfo.length;
var index = Math.round(Math.random()*(N-1));
var answer = FranceInfo[index];
this.response.speak(answer);
this.emit(':responseReady);
}
文件 2
var FranceInfo = [
'The language spoken in France is french',
'Paris is the capital of France',
];
您可以使用 fs
读取并将值作为数组存储在第二个文件中并在第一个文件中解析。
或
因为您在第一个文件中使用 require
,所以在第二个文件的末尾使用 module.exports = FranceInfo
,以便它可以加载到第一个
您必须更改信息文件才能导出数据。更改文件 2 以导出要访问的变量,如下所示:
var FranceInfo = [
'The language spoken in France is french',
'Paris is the capital of France',
];
module.exports.data = FranceInfo;
然后您可以像这样在第一个文件中要求该变量:
const FranceInfoData = require('./FranceInfo');
var FranceInfo = FranceInfoData.data;
那么您的 FranceInfo 变量将等于外部文件中的数组。
这不是唯一的方法,但它是最简单的方法之一。