如何将函数外部的variables传递给Firebase事件

以下是我在nodeJS服务器上运行的代码,我试图在触发'child_added'事件后立即发送短信

 // Twilio Credentials var accountSid = '<AccountSid>'; var authToken = '<authToken>'; var twilio = require("twilio"); var client = new twilio.RestClient(accountSid, authToken); // TWILIO Function client.messages.create({ to: "+12432056980", // This need to be obtained from firebase from: "+14352058756", body: "Hey There! Good luck on the bar exam!" }, function(err, message) { console.log(message.sid); }); 

下面是一旦孩子被添加到firebase数据库时触发的事件,我想在触发下面的事件时立即调用TWILIO函数(如上所示),并且从下面将移动号码variables传递给它function。

 ref.limitToFirst(1).on('child_added', function(snapshot) { // This function triggers the event when a new child is added var userDetails = snapshot.val(); var mobileNumber = userDetails.mobileNumber; //*** I would like to call the TWILIO CODE at this point and pass it the 'mobileNumber' parameter }); 

如果这两个操作在同一个文件中,您可以将Twilio调用包装在一个函数中,并在Firebase操作中调用它,如下所示:

 function sendSMS(dest, msg) { client.messages.create({ to: dest, from: "+14352058756", body: msg }, function(err, message) { console.log(message.sid); }); } ref.limitToFirst(1).on('child_added', function(snapshot) { var userDetails = snapshot.val(); var mobileNumber = userDetails.mobileNumber; sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!"); }); 

如果Twilio操作位于不同的文件中,则可以将其导出并要求使用Firebase

 //twiliofile.js module.exports.sendSMS = function(dest, msg) { client.messages.create({ to: dest, from: "+14352058756", body: msg }, function(err, message) { console.log(message.sid); }); } 

 //firebasefile.js var sms = require('./twiliofile.js'); ref.limitToFirst(1).on('child_added', function(snapshot) { var userDetails = snapshot.val(); var mobileNumber = userDetails.mobileNumber; sms.sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!"); });