简体   繁体   English

Alexa Lambda JS如何从外部.js文件访问数组数据

[英]Alexa lambda JS how to access array data from external .js file

i'm building an alexa skill in lambda with JS code. 我正在使用JS代码在lambda中构建alexa技能。 i have 2 files . 我有2个文件 one with regular code for alexa skill to work, and second file has an array with data that i will be needing when triggering an Inttent. 一个具有用于alexa技能的常规代码,第二个文件具有一个数组,该数组包含触发Inttent时需要的数据。

¿what code do i have to use in order to allow alexa read the array data from the second file? 我必须使用什么代码才能使alexa从第二个文件中读取数组数据?

file 1 文件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);

}

file 2 文件2

var FranceInfo = [

'The language spoken in France is french',

'Paris is the capital of France',

];

You could either read using fs and store the values as an array in the second file and parsed in the first. 您可以使用fs读取并将值作为数组存储在第二个文件中,然后在第一个文件中进行解析。

OR 要么

since you are using require in the first file, use module.exports = FranceInfo at the end of the second file so that it can be loaded into the first 因为使用的是require在第一文件中,使用module.exports = FranceInfo在第二个文件的末尾,以便它可以被加载到第一

You have to change your info file to export the data. 您必须更改您的信息文件才能导出数据。 Change your file 2 to export the variable you want to access like this: 更改文件2来导出要访问的变量,如下所示:

var FranceInfo = [

'The language spoken in France is french',

'Paris is the capital of France',

];

module.exports.data = FranceInfo;

And then you can require that variable in your first file like so: 然后,您可以在第一个文件中要求该变量,如下所示:

const FranceInfoData = require('./FranceInfo');

var FranceInfo = FranceInfoData.data;

Then your FranceInfo variable would be equal to the array in the external file. 然后,您的FranceInfo变量将等于外部文件中的数组。

This isn't the only way to do this, but it is one of the simplest. 这不是执行此操作的唯一方法,但这是最简单的方法之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM