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

发布于 2024-11-03 11:01:14 字数 1445 浏览 1 评论 0原文

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

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

});`

I'm new to JavaScript and creating classes/objects. I'm trying to wrap an open source library's code with some simple methods for me to use in my routes.

I have the below code that is straight from the source (sjwalter's Github repo; thanks Stephen for the library!).

I'm trying to export a file/module to my main app/server.js file with something like this:

var twilio = require('nameOfMyTwilioLibraryModule');

or whatever it is I need to do.

I'm looking to create methods like twilio.send(number, message)that I can easily use in my routes to keep my code modular. I've tried a handful of different ways but couldn't get anything to work. This might not be a great question because you need to know how the library works (and Twilio too). The var phone = client.getPhoneNumber(creds.outgoing); line makes sure that my outgoing number is a registered/paid for number.

Here's the full example that I'm trying to wrap with my own methods:

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);
            }
        });
    });
}

});`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-小熊_ 2024-11-10 11:01:14

只需添加您希望作为属性公开的函数到 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。

Simply add the function(s) you wish to expose as properties on the exports object. Assuming your file was named mytwilio.js and stored under app/ and looks like,

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);
    });
};

This file is mostly identical to what you already have with one crucial difference. It remembers whether the phone object has been initialized or not. If it hasn't been initialized, it simply throws an error if send is called. Otherwise it proceeds with sending the SMS. You could get fancier and create a queue that stores all messages to be sent until the object is initialized, and then sends em' all out later.

This is just a lazy approach to get you started. To use the function(s) exported by the above wrapper, simply include it the other js file(s). The send function captures everything it needs (initialized and phone variables) in a closure, so you don't have to worry about exporting every single dependency. Here's an example of a file that makes use of the above.

app/mytwilio-test.js

var twilio = require("./mytwilio");

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

If you don't like to include with the full/relative path of mytwilio.js, then add it to the paths list. Read up more about the module system, and how module resolution works in Node.JS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文