npm中node更新

by Ted Gross

泰德·格罗斯(Ted Gross)

如何在Node中管理NPM和功能时保持理智 (How to keep your sanity while managing NPM & functions in Node)

介绍 (Introduction)

In my career, I have trolled through hundreds of articles dealing with NodeJS and many full examples of NodeJS, either in the typical MEAN stack, or specific examples using various NPM modules. An integral part of writing in NodeJS is using NPM or Yarn to install libraries which do certain things. To give an example which all Node programmers will know of, there is the Express-Passport-JWT-Mongo NPM libraries.

在我的职业生涯中,我浏览了数百篇有关NodeJS的文章,以及许多关于NodeJS的完整示例,无论是在典型的MEAN堆栈中,还是在使用各种NPM模块的特定示例中。 NodeJS写作的一个不可分割的部分是使用NPM或Yarn安装可以完成某些功能的库。 举一个所有Node程序员都知道的例子,这里有Express-Passport-JWT-Mongo NPM库。

We all know the stack as well will not stop there. Express will probably also require installation of “body-parser” and “cors”, and possibly sub Express NPM modules. Don’t forget Lodash, Underscore, Moment…and the list goes on and on as there are thousands upon thousands of NPM modules to make use of.

我们都知道堆栈也不会停在那里。 Express可能还需要安装“ body-parser”和“ cors”,以及可能的子Express NPM模块。 别忘了Lodash,Underscore,Moment…之所以如此,因为有成千上万个NPM模块可以使用。

维护NPM模块结构 (Maintaining NPM Module Structure In A Sane Way)

Normally, when you review code snippets or systems in a search, or write your own, each file will contain the modules required for that specific file. The following code snippets are taken from real code snippets available on the net:

通常,当您在搜索中查看代码段或系统或编写自己的代码段时,每个文件都将包含该特定文件所需的模块。 以下代码段摘自网络上可用的真实代码段:

  • Please note for these examples the ‘var’ should be replaced with ‘let’ or ‘const’ depending upon what is being done.

    请注意,对于这些示例,根据所执行的操作,应将“ var”替换为“ let”或“ const”。

var express = require('express');var path = require('path');var favicon = require('serve-favicon');var logger = require('morgan');var bodyParser = require('body-parser');

Then another file will may start with:

然后另一个文件可能会以以下内容开头:

var morgan = require('morgan');var mongoose = require('mongoose');var passport = require('passport');

And a third file will start with:

第三个文件将以:

var mongoose = require('mongoose');var Schema = mongoose.Schema;var bcrypt = require('bcrypt-nodejs');

You can imagine the rest of the files and there are usually many, even in micro-services, of how they look.

您可以想象其余的文件,甚至在微服务中,通常还有很多文件的外观。

What makes this practice even worse, is that you can find ‘require’ in the middle of a file as well. In other words, code can go along for many lines and suddenly the coder will introduce yet another NPM module. This usually happens with inexperienced or non-organized coders, yet it is an incredibly common practice and wreaks havoc with understanding and debugging code.

使这种做法更糟的是,您也可以在文件中间找到“ require” 。 换句话说,代码可能会走很多行,突然,编码器将引入另一个NPM模块。 这通常发生在没有经验或没有组织的编码人员的情况下,但是这是非常普遍的做法,对理解和调试代码造成了严重破坏。

The problem as you can well see, is this plethora of NPM modules, sooner rather than later will cause a huge headache in maintaining a system, especially within a team of programmers, who need to know what has already been installed and is available and what has not.

正如您所看到的那样,问题是过多的NPM模块,而不是迟早会引起维护系统的巨大麻烦,尤其是在一组程序员中,他们需要知道已经安装了什么,可以使用什么以及什么。还没有。

Node programmers are notorious for installing, testing and discarding NPM modules, (I admit to being one of them). The question of course is, how to maintain sanity, order, and most importantly control over installed NPM modules and a common method of calling them.

节点程序员以安装,测试和丢弃NPM模块而臭名昭著(我承认是其中之一)。 当然,问题是如何保持理智,秩序,最重要的是如何控制已安装的NPM模块以及调用它们的常用方法。

Fortunately, Node allows for a fairly simple method of dealing with these problems. The following is a method I use for back-end teams dealing with the stack. It keeps things orderly, easy to find, and everyone knowing what is installed and not installed in the system. It also allows for clean uninstalls when an NPM module is no longer needed.

幸运的是,Node提供了一种相当简单的方法来处理这些问题。 以下是我用于后端团队处理堆栈的方法。 它使事情井井有条,易于查找,并且每个人都知道系统中已安装和未安装的内容。 当不再需要NPM模块时,它还允许全新卸载。

If you are a “functional” programmer, in other words not everything must be OOP with classes and “this->”, the following may actually allow you to reconsider a whole new method of using functions and stored procedures.

如果您是“函数式”程序员,换句话说,不是所有的东西都必须是带有类和“ this->”的OOP,实际上,以下内容可能使您重​​新考虑使用函数和存储过程的全新方法。

My suggestion would be to create a directory under your root project directory. I usually call this directory “env”, but you can call it whatever you like. “env” is where I keep all my function libraries and stored procedures including, if used, the environment file needed by the “dotenv” NPM library. (The environment variables can be held anywhere, they do not need to be held in the root project directory. Yet a discussion about environment variables and “dotenv” is for another article.) In other words, your “env” directory should only contain files which should be required or accessed by parts of the systems.

我的建议是在根项目目录下创建一个目录。 我通常将此目录称为“ env” ,但是您可以随意命名。 “ env”是我所有函数库和存储过程的存放地,其中包括“ dotenv” NPM库所需的环境文件(如果使用的话)。 (环境变量可以保存在任何地方,它们不需要保存在根项目目录中。关于环境变量和“ dotenv”的讨论将在另一篇文章中进行。)换句话说,您的“ env”目录应仅包含系统的某些部分需要或访问的文件。

In the “env” directory off the root, create a file called “helperMods.js”. (Again, you can call this file whatever you like.) Additionally, if your system is going to use many NPM modules, or those just used for development purposes (such as “chalk”), you my want to divide this into two or three files. However, for our simple example we will use one file.

在根目录下的“ env”目录中,创建一个名为“ helperMods.js”的文件。 (同样,您可以随意调用此文件。)此外,如果您的系统要使用许多NPM模块,或仅用于开发目的的模块(例如“粉笔”),您希望将其分为两个或两个。三个文件。 但是,对于我们的简单示例,我们将使用一个文件。

module.exports = {    request: require("request"), //used for request http    fs: require('fs'),    path: require('path'),    chalk: require('chalk'),    moment: require('moment'),    express: require('express'),    session: require('express-session'),    eJWT: require('express-jwt'),    bodyParser: require('body-parser'),    cors: require('cors'),    passport: require('passport'),    passportLocal: require('passport-local'),    crypto: require('crypto'),    dotenv: require('dotenv'),    jwt: require('jsonwebtoken'),    jwtclaims: require('jwt-claims'),    redis: require('redis'),    mongodb: require('mongodb'),    mongoose: require('mongoose'),    assert: require('assert'),    shortid: require('shortid'),    badWords: require('bad-words'),    enum: require('enum'),    errorHandler: require('errorhandler'),    morgan: require('morgan')};

First, install an NPM module you want to use, for example:

首先,安装要使用的NPM模块,例如:

npm i jsonwebtoken --s

Now decide upon a caller for that module. For instance, in the above file, jsonwebtoken is defined first as “jwt”. Then require the actual module you installed. So, the line will read:

现在确定该模块的调用方。 例如,在上面的文件中,jsonwebtoken首先定义为“ jwt”。 然后要求您安装的实际模块。 因此,该行将显示为:

jwt: require('jsonwebtoken'),

(The comma at the end is due to the JSON format of the file.)

(最后的逗号是由于文件的JSON格式。)

The things to be aware of in this file are as follows:

该文件中需要注意的事项如下:

1. Keep your calling names distinct.

1.保持您的通话名称不同。

2. Despite what you see above, I would alphabetize according to calling names or NPM module alphabet order.

2.尽管您在上面看到了什么,我还是会根据呼叫名称或NPM模块的字母顺序来按字母顺序排列。

3. Remember, as well, even if it is a built-in NodeJS module such as “crypto” (yes “crypto” is now finally part of the internal NodeJS) or “request” you need to require it.

3.同样,请记住,即使它是内置的NodeJS模块,例如“ crypto”(是的,“ crypto”现在终于成为内部NodeJS的一部分)或“请求”,您也需要使用它。

4. Indeed, if you do require many “native” modules you can separate these into files which can all be called from the first few lines in each file you run.

4.确实,如果确实需要许多“本机”模块,则可以将它们分成文件,可以在运行的每个文件的前几行中全部调用它们。

5. Remember, “namepaces” will protect you from loading a module twice into memory. Once you call that module in your require, even if you call it again from another file, it will not take up more or “duplicate” memory.

5.请记住,“ namepaces”将保护您避免两次将模块加载到内存中。 一旦在您的需求中调用了该模块,即使您从另一个文件中再次调用它,它也不会占用更多或“重复”的内存。

Once you have your file setup, the method of calling from any file is fairly easy.

设置文件后,从任何文件调用的方法都非常简单。

Each file you set up or use, should start with two (or more) lines depending upon the modules you need to require. For example:

您设置或使用的每个文件应以两行(或更多行)开头,具体取决于您需要的模块。 例如:

"use strict";const helpMods = require("./env/helperMods");

Those above lines above will require all the modules in your file. It then becomes a simple method to call them using dot notation.

上面的那些行将需要文件中的所有模块。 然后,它成为使用点表示法调用它们的简单方法。

For instance, if you need to call the badWords module, your dot notation will look like this:

例如,如果您需要调用badWords模块,则点符号将如下所示:

helpMods.badWords.(do whatever needs to be done normally here)

If you forget the helpMods, an IDE such as WebStorm will throw you out an error warning that the module has not been required which will immediately tell you that you forgot the correct dot notation or that you have forgotten to include that module in your main exports file.

如果您忘记了helpMods,则诸如WebStorm之类的IDE会向您抛出一条错误警告,提示您不需要该模块,该警告将立即告诉您您忘记了正确的点符号或忘记了将该模块包括在主要导出中文件。

明智地维护用户功能 (Maintaining User Functions In A Sane Way)

Again, when looking at many examples you will find functions within the file. Many times, these functions are a “one-off”, in other words specifically used for a very specific situation which will not repeat itself. Or will it?

同样,在查看许多示例时,您将在文件中找到函数。 很多时候,这些功能是“一次性的”,换句话说,专门用于非常特殊的情况,这些情况不会重复出现。 还是会?

In years of experience I have learned that once you have a function running correctly, there is a good chance you will use it again from another file. Perhaps the parameters may be different, or you may need to add to the parameters it receives (easily done with a good IDE), but chances are you will use it again.

在多年的经验中,我了解到一旦功能正常运行,您很有可能会从另一个文件中再次使用它。 也许参数可能有所不同,或者您可能需要将其添加到接收的参数中(通过良好的IDE可以轻松完成), 但是您可能会再次使用它

For this reason, I maintain a set of function libraries in the “env” directory. I usually try to divide these functions into logical structures. For instance, all CRUD and other DB activities will go into one function library file. All security functions will go into another. This is just a suggestion.

因此,我在“ env”目录中维护了一组函数库。 我通常尝试将这些功能划分为逻辑结构。 例如,所有CRUD和其他DB活动将进入一个功能库文件。 所有安全功能都将纳入另一个功能。 这只是一个建议。

What this type of programming does:

这种编程的作用是:

  • Gives you and your team control over the environment.使您和您的团队可以控制环境。
  • Reduces the requires of specific modules over and over again in each file.一遍又一遍地减少每个文件中特定模块的需求。
  • Grants immediate access to NPM modules which you may have not thought you needed in a file.授予对NPM模块的即时访问权限,而您可能认为文件中不需要这些模块。
  • Uses standard dot notation, without any workarounds.使用标准的点符号,没有任何变通办法。
  • Allows you to divide up your structure in any way you deem fit, including calling functions in function files etc. in this manner. However, a function file is not written in the same type of structure. You will require:允许您以您认为合适的任何方式划分结构,包括以这种方式调用函数文件中的函数等。 但是,功能文件不是以相同类型的结构编写的。 您将需要:
"use strict";const helpMods = require("./env/helperMods");

And any other module files you decided upon.

以及您决定的任何其他模块文件。

For this example we will use a few functions, separated into order for our system Then write and define all functions, with callbacks, promises or async/await. Let us call the file “generalFuncs.js” Each function though does have a name.

在此示例中,我们将使用一些功能,这些功能按系统顺序排列,然后使用回调,promise或async / await编写和定义所有功能。 让我们将文件称为“ generalFuncs.js”,尽管每个函数都有一个名称。

Function(getExactTime(passed params go in here){/do stuff in here}
Function(logFile(passed params go in here){//do stuff in here}

Add as many functions as you need to this file. So, at the end of the function file you should write:

向此文件添加所需数量的功能。 因此,在功能文件的末尾,您应该编写:

module.exports = {getExactTime, logfile, HTMLResponse, getRemoteConnect, doesKeyExist, generateUniqueKey, restartAll, createDateFromString};

The above will allow these functions to be available in dot.notation to any file you add the following:

上面的代码允许这些功能以dot.notation的形式提供给您添加以下文件的任何文件:

"use strict";const helpMods = require("./env/helperMods");const generalFuncs = require (../env/generalFuncs");

Now when you use the function “getExactTime” you access it as follows:

现在,当您使用函数“ getExactTime”时,可以按以下方式访问它:

generalFuncs.getExactTime(whatever is needed goes here);

As an added plus in any good IDE, you will be able to see which functions are not ever exported as they will never be required in any system.

作为任何良好IDE的附加功能,您将能够看到从未导出过哪些功能,因为它们在任何系统中都将不再需要。

结论 (Conclusion)

The above methods will allow you to maintain control and understanding of what is being used in the system. The function files will allow refactoring of functions along the route whenever it needs to be done. Dot notation will allow you to call the modules or functions in a simple orderly fashion.

以上方法将使您可以保持控制和了解系统中正在使用的内容。 只要需要,功能文件将允许沿路线重构功能。 点表示法使您可以以简单有序的方式调用模块或函数。

It does add a further level into your directory structure which may drive you crazy accessing them from other sub-directories, unless you know exactly how Node handles directory structures (which you should know anyway). If you would rather not do this you can leave them in your root app directory.

它确实在目录结构中增加了一层,可能使您疯狂地从其他子目录访问它们,除非您确切地知道Node如何处理目录结构(无论如何您都应该知道)。 如果您不想这样做,可以将其保留在根应用目录中。

None of this, by the way, will interfere with GitHub Versions or version controls. Indeed, checking, refactoring and testing will become that much easier. Single lines can be marked only for development systems others for production systems.

顺便说一下,这些都不会干扰GitHub版本或版本控制。 实际上,检查,重构和测试将变得更加容易。 单行只能标记为开发系统,其他标记为生产系统。

If you can wrap your ahead around this coding style, at least in terms of modules and possibly functions, you will find your code cleaner, easier to read, available to the entire team & easier to refactor.

如果您至少可以在模块和可能的功能方面围绕这种编码风格进行开发,您会发现您的代码更简洁,更易于阅读,可供整个团队使用和更易于重构。

________________________________________________________

________________________________________________________

About the Author: Ted Gross served as a CTO for many years with an expertise in database technology, NodeJS, MongoDB, Encryption, PHP and OOP. He has expertise in Virtual World Technologies & Augmented Reality. He has also published many articles on technological topics especially on Big Data & Chaos Theory (in professional journals and online @ Medium & LinkedIn). He is also an author of literary fiction, children’s books and various non-fiction articles. His short story collection, “Ancient Tales, Modern Legends” has received excellent reviews.

关于作者:Ted Gross曾担任CTO多年,在数据库技术,NodeJS,MongoDB,Encryption,PHP和OOP方面具有专业知识。 他在虚拟世界技术和增强现实方面拥有专业知识。 他还发表了许多有关技术主题的文章,特别是有关大数据和混沌理论的文章(在专业期刊上以及在线@ Medium&LinkedIn)。 他还是文学小说,儿童读物和各种非小说类文章的作者 。 他的短篇小说集“古代故事,现代传奇”获得了好评。

Ted can be reached via email: tedwgross@gmail.com; Twitter (@tedwgross); LinkedIn; Medium

可以通过以下电子邮件与Ted联系:tedwgross@gmail.com; Twitter (@tedwgross); 领英 ; 中

翻译自: https://www.freecodecamp.org/news/how-to-keep-your-sanity-while-managing-npm-functions-in-node-9a5889cce80d/

npm中node更新

npm中node更新_如何在Node中管理NPM和功能时保持理智相关推荐

  1. node 单元测试_如何在Node中模拟对单元测试的请求

    node 单元测试 by Edo Rivai 由Edo Rivai 如何在Node中模拟对单元测试的请求 (How to mock requests for unit testing in Node) ...

  2. 符号在excel中的引用_如何在Excel中添加项目符号

    &符号在excel中的引用 There's no built-in feature for bullets in Excel, like there is in a Word document ...

  3. excel中去重计数_如何在Excel中计数

    excel中去重计数 There are lots of different ways to count things in Excel – maybe you need to count the n ...

  4. aws中部署防火墙_如何在AWS中设置自动部署

    aws中部署防火墙 by Harry Sauers 哈里·绍尔斯(Harry Sauers) 如何在AWS中设置自动部署 (How to set up automated deployment in ...

  5. python移动文件中某个内容_如何在Python中移动文件

    如何在Python中移动文件 我查看了Python $ mv ...接口,但无法找到移动文件的方法. 我如何在Python中执行相当于$ mv ...的操作? >>> source_ ...

  6. 如何在mysql中创建过程_如何在MySQL 中创建存储过程?

    问题阐述 自MySQL 5.0 开始,MySQL 就支持存储过程.存储过程是一些被用户定义的SQL 语句集合.一个存储程序是可以被存储在服务器中的一套SQL 语句.存储过程可以被程序.触发器或另一个存 ...

  7. python3提取字符串中的数字_如何在Python中从字符串中提取数字?

    14 回复 | 直到 1 年前 1 430 3 年前 如果只想提取正整数,请尝试以下操作: >>> str = "h3110 23 cat 444.4 rabbit 11 ...

  8. java中为什么同步_如何在Java中同步工作

    如何在Java中同步工作 首先, 这是一个示例 : public class Deadlock { static class Friend { private final String name; p ...

  9. java文件中获取创建日期_如何在Java中获取文件的上次修改日期

    java文件中获取创建日期 Sometimes we need to get the file last modified date in Java, usually for listeners li ...

最新文章

  1. semilogx 多条曲线_怎么让两个指数在一个坐标,matlab里怎样一个坐标上显示多个曲线,而且横轴要用指数形式的?谢谢...
  2. 【win32汇编】0x01 开篇一些乱七八糟的话
  3. Mysql8.0之后没有缓存功能
  4. js引擎执行代码的基本流程
  5. error: default argument given for parameter 4
  6. float,absolute脱离文档流的总结
  7. 干货 · UI设计|APP引导页面可临摹素材
  8. 20年研发管理经验谈(七)
  9. kafka(五)服务器配置优化
  10. 【JAVA程序设计】从HelloWorld开始
  11. HDU2095find your present (2)【hash】
  12. HTML+CSS基础学习:HTML
  13. win7与internet时间同步出错_Win7电脑时间同步出错怎么办?Win7电脑时间同步出错的解决方法...
  14. ckplayer在线播放流媒体
  15. TILERA--Makefile实例
  16. Android 启动过程介绍
  17. 「大冰撸设计模式」java 创建型模式之单例模式
  18. Linux下git clone速度奇慢的有效解决办法(亲测有效)
  19. matlab稳定性实验分析,实验 控制系统稳定性分析的MATLAB实现
  20. PowerPoint输出图片分辨率设置

热门文章

  1. 如何在面试中回答「你最大的缺点是什么」?
  2. 神器集合!这12个免费工具可以让您的工作更高效
  3. Centos7 GNOME Desktop桌面版-调整屏幕分辨率
  4. laragon yii
  5. @Cacheable失效
  6. python爬取芒果TV《乘风破浪的姐姐》弹幕数据(已完成)
  7. python中的抽象类
  8. 机器学习实战——3.1 决策树的构造
  9. 机器学习实战|决策树
  10. Excel技能之实用技巧,高手私藏