2

我是 JavaScript 和创建类/对象的新手。我正在尝试用一些简单的方法来包装开源库的代码,以便在我的路线中使用。

我有以下直接来自代码的代码(sjwalter 的 Github 存储库;感谢 Stephen 提供的库!)。

我正在尝试将文件/模块导出到我的主 app/server.js 文件,如下所示:

var twilio = require('nameOfMyTwilioLibraryModule');

或者我需要做的任何事情。

我正在寻找twilio.send(number, message)可以在路线中轻松使用的方法来保持我的代码模块化。我尝试了几种不同的方法,但没有任何效果。这可能不是一个好问题,因为您需要了解库的工作原理(以及 Twilio)。该var phone = client.getPhoneNumber(creds.outgoing);线路确保我的拨出号码是注册/付费号码。

这是我试图用自己的方法包装的完整示例:

var TwilioClient = require('twilio').Client,
Twiml = require('twilio').Twiml,
creds = require('./twilio_creds').Credentials,
client = new TwilioClient(creds.sid, creds.authToken, creds.hostname),
// Our numbers list. Add more numbers here and they'll get the message
numbers = ['+numbersToSendTo'],
message = '',
numSent = 0;

var phone = client.getPhoneNumber(creds.outgoing);
phone.setup(function() {

for(var i = 0; i < numbers.length; i++) {
    phone.sendSms(numbers[i], message, null, function(sms) {
        sms.on('processed', function(reqParams, response) {
            console.log('Message processed, request params follow');
            console.log(reqParams);
            numSent += 1;
            if(numSent == numToSend) {
                process.exit(0);
            }
        });
    });
}

});`

4

1 回答 1

2

只需添加您希望作为exports对象属性公开的函数。假设您的文件被命名mytwilio.js并存储在下面app/,看起来像,

应用程序/mytwilio.js

var twilio = require('twilio');
var TwilioClient = twilio.Client;
var Twiml = twilio.Twiml;
var creds = require('./twilio_creds').Credentials;
var client = new TwilioClient(creds.sid, creds.authToken, creds.hostname);

// keeps track of whether the phone object
// has been populated or not.
var initialized = false;
var phone = client.getPhoneNumber(creds.outgoing);
phone.setup(function() {
    // phone object has been populated
    initialized = true;
});

exports.send = function(number, message, callback) {
    // ignore request and throw if not initialized
    if (!initialized) {
        throw new Error("Patience! We are init'ing");
    }
    // otherwise process request and send SMS
    phone.sendSms(number, message, null, function(sms) {
        sms.on('processed', callback);
    });
};

该文件与您已经拥有的文件基本相同,但有一个关键区别。它记住phone对象是否已经初始化。如果它还没有被初始化,它只是在send被调用时抛出一个错误。否则,它将继续发送 SMS。您可以更花哨并创建一个队列来存储发送的所有消息,直到对象被初始化,然后稍后将它们全部发送出去。

这只是一种让您入门的懒惰方法。要使用上述包装器导出的函数,只需将其包含在其他 js 文件中即可。该send函数在闭包中捕获它需要的所有内容(initializedphone变量),因此您不必担心导出每个依赖项。这是使用上述内容的文件示例。

应用程序/mytwilio-test.js

var twilio = require("./mytwilio");

twilio.send("+123456789", "Hello there!", function(reqParams, response) {
    // do something absolutely crazy with the arguments
});

如果您不喜欢包含 的完整/相对路径mytwilio.js,请将其添加到路径列表中。阅读有关模块系统的更多信息,以及模块解析在 Node.JS 中的工作原理。

于 2011-04-28T01:58:56.793 回答