创建可导出对象或模块,用CommonJS/NodeJS javascript包装第三方库

创建可导出对象或模块,用CommonJS/NodeJS javascript包装第三方库,javascript,module,node.js,export,twilio,Javascript,Module,Node.js,Export,Twilio,我不熟悉JavaScript和创建类/对象。我试图用一些简单的方法来包装一个开源库的代码,以便在我的路线中使用 下面的代码直接来自于(sjwalter的Github repo;感谢Stephen提供的库!) 我正在尝试将文件/模块导出到我的主app/server.js文件,如下所示: var twilio = require('nameOfMyTwilioLibraryModule'); 或者我需要做什么 我希望创建一些方法,比如twilio.send(number,message),我可以在

我不熟悉JavaScript和创建类/对象。我试图用一些简单的方法来包装一个开源库的代码,以便在我的路线中使用

下面的代码直接来自于(sjwalter的Github repo;感谢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);
            }
        });
    });
}
var TwilioClient=require('twilio')。客户端,
Twiml=require('twilio')。Twiml,
信誉=要求('./twilio_信誉')。信誉,
client=新的TwilioClient(creds.sid、creds.authToken、creds.hostname),
//我们的号码表。在这里添加更多数字,他们就会收到消息
数字=['+numbersToSendTo'],
消息=“”,
numSent=0;
var phone=client.getPhoneNumber(creds.outgoing);
phone.setup(函数(){
对于(变量i=0;i
}))`

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

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);
    });
};
var twilio = require("./mytwilio");

twilio.send("+123456789", "Hello there!", function(reqParams, response) {
    // do something absolutely crazy with the arguments
});
此文件与您已有的文件基本相同,但有一个关键区别。它会记住
手机
对象是否已初始化。如果尚未初始化,则在调用
send
时将抛出一个错误。否则,它将继续发送SMS。您可以使用fancier创建一个队列,该队列存储在对象初始化之前要发送的所有消息,然后在稍后将它们全部发送出去

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

app/mytwilio test.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);
    });
};
var twilio = require("./mytwilio");

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

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

谢谢Anurag!在答案底部的回调中,什么是
reqParams
?我理解正常的HTTP回调参数,但在本例中它们是用于什么的?@John-这与您的示例中的回调相同(
sms.on('processed',function(reqParams,response)…
),可由包装器的客户端提供,以保持灵活性。它是此库在发送SMS后发出的
已处理的
事件的一部分。在源代码中查看此事件意味着
reqParams
是请求主体,
response
Twiml.response
的对象。