使用CommonJS / NodeJS javascript创build可导出对象或模块以包装第三方库
我是JavaScript新手,并创build类/对象。 我试图用一些简单的方法来打包一个开源库的代码,供我在路由中使用。
我有下面的代码是直接从源 (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); } }); }); }
});`
只需将您希望公开的函数添加为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
才会引发错误。 否则,继续发送短信。 你可能会变得更加奇特,并创build一个队列来存储所有要发送的消息,直到对象被初始化,然后发送em'all'。
这只是一个懒惰的方法,让你开始。 要使用上面的包装器导出的函数,只需将其包含在其他js文件中即可。 send
函数在闭包中捕获它需要的所有东西( initialized
和phone
variables),所以你不必担心导出每一个依赖项。 这是一个使用上面的文件的例子。
应用程序/ mytwilio-test.js
var twilio = require("./mytwilio"); twilio.send("+123456789", "Hello there!", function(reqParams, response) { // do something absolutely crazy with the arguments });
如果您不想包含mytwilio.js
的完整path/相对path, mytwilio.js
其添加到path列表中。 阅读关于模块系统的更多信息,以及Node.JS中的模块分辨率是如何工作的。