相关疑难解决方法(0)

Javascript - 在NodeJS中构造帮助程序函数的最佳方法

我正在尝试为我的NodeJS项目构建一组utils.这些帮助程序将包括:text utils(如子字符串,控制台日志记录等),以及更具体的帮助程序,如解析推文的文本.

因此,我试图将模块划分为不同的文件,并清楚地了解每个事情的意图.

例如,我想实现这个目标:

var helpers = require("helpers");

var Utils = new helpers.Utils();

// working with text
Utils.text.cleanText("blahblalh");
// working with a tweet
Utils.twitter.parseTweet(tweet);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我通过调用非常具体的方法和子方法来使用Utils来处理不同的事情.

我试图了解继承如何在这里工作,但我有点失落.

这就是我正在做的(一些粗略的示例代码):

//node_modules/helpers/index.js

var Text = require('./text');
var Twitter = require('./twitter');

function Utils() {

}

Utils.prototype.text = {
    cleanText: function(text) {
        Text.cleanText(text);
    }
};

Utils.prototype.twitter = {
    parseTweet(tweet) {
        Twitter.parseTweet(tweet);
    }
};
Run Code Online (Sandbox Code Playgroud)

//node_modules/helpers/text.js

function Text() {

}

Text.prototype.cleanText = function(text) {
    if (typeof text !== 'undefined') {
        return text.replace(/(\r\n|\n|\r)/gm,"");
    }
    return null;
};

module.exports = …
Run Code Online (Sandbox Code Playgroud)

javascript node.js

27
推荐指数
2
解决办法
4万
查看次数

标签 统计

javascript ×1

node.js ×1