使用CommonJS/NodeJS创建可导出的对象或模块以包装第三方库javascript
我是JavaScript新手,并创建类/对象。我想用一些简单的方法来打包开源库的代码,以供我在我的路由中使用。使用CommonJS/NodeJS创建可导出的对象或模块以包装第三方库javascript
我有下面的代码,直接从source(sjwalter的Github回购;感谢斯蒂芬图书馆!)。
我想文件/模块导出到我的主要应用程序/ 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);
}
});
});
}
});`
只需添加功能(S)你希望作为对性能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
,它只会抛出一个错误。否则,它会继续发送短信。你可能会更喜欢它,并创建一个队列,将所有消息存储为,直到对象初始化,然后将em'全部发送出去。
这只是一个懒惰的方法来让你开始。要使用上述包装器导出的函数,只需将其包含在其他js文件中即可。 send
函数在闭包中捕获它需要的所有东西(initialized
和phone
变量),所以您不必担心导出每一个依赖项。这是一个使用上述文件的例子。
应用程序/ mytwilio-test.js
var twilio = require("./mytwilio");
twilio.send("+123456789", "Hello there!", function(reqParams, response) {
// do something absolutely crazy with the arguments
});
如果你不喜欢包括具有mytwilio.js
全/相对路径,然后将其添加到路径列表。阅读关于模块系统的more,以及Node.JS中的模块分辨率是如何工作的。
谢谢Anurag!在回答的底部,有什么是'reqParams'?我理解普通的HTTP回调参数,但是在这个例子中它们是什么? – JohnAllen 2011-04-28 02:20:01
@John - 它与您的示例('sms.on('processed',function(reqParams,response)..')的回调相同,可由包装的客户端提供以保持灵活性。发送SMS后,该库发出的'processed'事件。在源代码中查看[line](https://github.com/sjwalter/node-twilio/blob/master/lib/twilio.js#L226)意味着'reqParams'是请求主体,'response'是“Twiml.Response”的一个对象。 – Anurag 2011-04-28 05:39:22