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

Create exportable object or module to wrap third-party library with CommonJS/NodeJS javascript

本文关键字:NodeJS CommonJS javascript 包装 第三方 对象 模块 创建      更新时间:2023-09-26

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

我有下面的代码是直接从源代码(sjwalter的Github repo;谢谢Stephen提供的图书馆!)。

我试图导出一个文件/模块到我的主应用程序/服务器.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/下,如下所示

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变量),因此您不必担心导出每个依赖项。下面是一个使用上述方法的文件示例。

app/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中是如何工作的。