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

标签 javascript module node.js export twilio

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

我有以下直接来自 source 的代码(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);
            }
        });
    });
}

});`

最佳答案

只需将您希望作为属性公开的函数添加到 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 的完整/相对路径,请将其添加到路径列表中。阅读 more,了解模块系统,以及模块解析在 Node.JS 中的工作原理。

关于javascript - 创建可导出对象或模块以使用 CommonJS/NodeJS javascript 包装第三方库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5812228/

相关文章:

javascript - 从 Javascript Image() 元素构造函数获取图像属性

javascript - Node.js 和碎片化

perl - 事件状态 Perl : Unable to download modules using ppm

android - react native 错误 : Unable to resolve module `AccessibilityInfo`

module - 模块和存在的区别

mysql - 使用 React.js 和 Express 删除发布到 MySQL 的帖子

node.js - 使用 Node.js 通过 Azure 在 telegram 上托管机器人

node.js - 错误: Missing title - google calendar create or update

javascript - 避免 "Cannot set headers after they are sent"错误的最佳方法

javascript - 我要如何循环遍历 Polymer 1.0 元素中的一组 DOM 元素?