Javascript 在 NodeJS 中构建辅助函数的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30273993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:54:13  来源:igfitidea点击:

Best way to structure helpers functions in NodeJS

javascriptnode.js

提问by Anonymous

I am trying to build a set of utils for my NodeJS project. These helpers will include: text utils (like substringing, console logging etc.), and more specific helpers like parsing the text of a tweet.

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

So I am trying to divide the module in different files and with a very clear idea of what each thing is meant to do.

所以我试图将模块划分到不同的文件中,并对每件事的意义有一个非常清晰的认识。

For example I would like to achieve this:

例如,我想实现这一点:

var helpers = require("helpers");

var Utils = new helpers.Utils();

// working with text
Utils.text.cleanText("blahblalh");
// working with a tweet
Utils.twitter.parseTweet(tweet);

As you can see I am using Utils for different things, by calling very specific methods and sub methods.

正如您所看到的,我通过调用非常具体的方法和子方法将 Utils 用于不同的事情。

I tried to understand how inheritance works here but I got a little bit lost.

我试图理解继承在这里是如何工作的,但我有点迷失了。

This is what I am doing (some rough sample code):

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

//node_modules/helpers/index.js

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

//node_modules/helpers/text.js

//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 = Text;

//node_modules/helpers/twitter.js

//node_modules/helpers/twitter.js

function Twitter() {

};

Twitter.prototype.parseTweet = function(data) {
    return data;
};

module.exports = Twitter

Is this a correct way? Am I doing something wrong or that could slow down the performances, etc?

这是正确的方法吗?我做错了什么或者可能会减慢表演等?

回答by cpentra1

To clarify how I'm understanding your post, I see two questions:

为了澄清我如何理解您的帖子,我看到了两个问题:

  • How do I structure code/methods within files, files that represent a category of utility functions
  • How do I organize the those categorical files into one larger library
  • 我如何在文件中构建代码/方法,文件代表一类实用程序功能
  • 如何将这些分类文件组织到一个更大的库中

Structuring methods within a category

类别内的构造方法

Rather than making all of the category specific functions methods of objects (e.g. Twitter or Text), you could just export the functions in files named after them. Since it seems you are passing in the data you want to use, there is no need to make the functions instance methods of some empty class.

与其使对象(例如 Twitter 或 Text)的所有类别特定函数方法成为方法,您还可以将函数导出到以它们命名的文件中。由于您似乎正在传入您要使用的数据,因此无需创建某些空类的函数实例方法。

If your usage patterns of Twitter or Text usually have class variables you want to keep state on, and you want to instantiate Text or Twitter objects to use your examples, then I suppose that would be appropriate. When I setup util libs in my projects it usually is a bunch of exported functions that make up a module, rather than an exported javascript class.

如果您对 Twitter 或 Text 的使用模式通常具有您想要保持状态的类变量,并且您想要实例化 Text 或 Twitter 对象以使用您的示例,那么我认为这是合适的。当我在我的项目中设置 util libs 时,它通常是一组组成模块的导出函数,而不是导出的 javascript 类。

To provide an example of what a text.js file made up of text-based utility functions might look like:

提供一个由基于文本的实用程序函数组成的 text.js 文件的示例:

module.exports = {
    cleanText:function(text) {
        // clean it and return
    },

    isWithinRange(text, min, max) {
        // check if text is between min and max length
    }
}

Alternatively, you could do it this way:

或者,您可以这样做:

exports.cleanText = function(text) {
    // clean it and return
}

exports.isWithinRange = function (text, min, max) {
    // check if text is between min and max length
}

Structuring utility category files to make a larger utility library

构建实用程序类别文件以制作更大的实用程序库

As far as organizing the utility methods, Luca's example is nice. I've organized some similarly like this:

就组织实用方法而言,Luca 的示例很好。我已经组织了一些类似的事情:

utils-module/
    lib/
        text.js  <-- this is the example file shown above
        twitter.js
    test/
    index.js

Where index.js does something like

index.js 在哪里做类似的事情

var textUtils = require('./lib/text');

exports.Text = textUtils;

Then when I want to use the util lib in say some User model in my node API, it's simply:

然后,当我想在我的节点 API 中的某个用户模型中使用 util lib 时,它很简单:

/*
 * Dependencies
 */
var textUtils = require('path/to/lib').Text;

/*
 * Model
 */
function User() {}

/*
 * Instance Methods
 */
User.prototype.setBio = function(data) {
    this.bio = textUtils.cleanText(data);
}

module.exports = User;

Hope that helps. When I was first learning it was very helpful to look at popular, well-respected libraries to see how more experienced node/javascript devs were doing things. There are so many good (and bad) ones out there!

希望有帮助。当我第一次学习时,查看流行的、备受推崇的库以了解更有经验的 node/javascript 开发人员是如何做事是非常有帮助的。那里有很多好的(和坏的)!

回答by Luca Colonnello

You can see a utils library example with lodash.

你可以看到一个带有 lodash 的 utils 库示例。

Lodash is an utility lib like underscorejs. This library have file sustem structure like your.

Lodash 是一个类似于 underscorejs 的实用程序库。这个库有像你这样的文件系统结构。

It divides the functions in categories. Each category is a folder with an index.js file that includes into a namespace (literal object) each functions for that category!

它按类别划分功能。每个类别都是一个带有 index.js 文件的文件夹,该文件包含该类别的每个函数的命名空间(文字对象)!

Lodash/
   Objects/
       Function1.js
       Functions2.js
       ....
       Index.js
   Array/
       Function1.js
       ...
       Index.js

Then in your code you can do this:

然后在你的代码中你可以这样做:

var objectsUtils = require("lodash/objects");
var foreach = require("lodash/array/each");

You can create a similar file system structure in order to have more flexibility. You can require the entire lib, only one namespace or a single function.

您可以创建类似的文件系统结构以获得更大的灵活性。您可以需要整个库,只有一个命名空间或单个函数。

This is better for performance, because you use only what you need and have a memory usage gain.

这对性能更好,因为您只使用您需要的内容并且获得了内存使用量。