NodeJS code organization and deployment

  Before using NodeJS programming, in order to have a good start, first of all you need to prepare the directory structure of the code and deployment, as fellow first house scaffolding. This chapter describes the various knowledge associated with it.

A module path parsing rules

  We already know that requirethe function supports a slash ( /) or letter ( C:) at the beginning of the absolute path, also supports ./relative paths beginning. But the two paths between modules to establish a strong coupling relationship, once the location of a storage module file needs to be changed, the code to use other modules of this module also need to follow the adjustment, led by a launch becomes systemic. Thus, requirethe function of the third form of support path, similar wording foo/barand sequentially the following rules resolve the path, until you find the position of the module.

1, built-in module

  If passed to requirethe function is built NodeJS module name, path resolution not return directly export the object inside the module, for example require('fs').

2, node_modules directory

  NodeJS define a special node_modulesdirectory for storing module. For example, the absolute path of a module that /home/user/hello.jsis used in the module require('foo/bar')when the module is loaded mode, then turn NodeJS try to use the following path.

/home/user/node_modules/foo/bar
/home/node_modules/foo/bar
/node_modules/foo/bar

3, NODE_PATH environment variable

  Similar to the PATH environment variable, NodeJS allowed to specify additional module search path by NODE_PATH environment variable. NODE_PATH environment variable that contains one or more directory path, the path between the use of Linux in the :separated, used in Windows ;are separated. For example, it defines the following NODE_PATH environment variables:

NODE_PATH=/home/user/lib:/home/lib

  When require('foo/bar')the time mode load modules, the attempt to turn NodeJS following path.

/home/user/lib/foo/bar
/home/lib/foo/bar

Second, the package (package)

  We already know the basic unit of JS JS module is a single file, but more complex modules often consists of multiple sub-modules. In order to facilitate the management and use, we can put a large block of a plurality of sub-modules are called , and all sub-modules in the same directory .

  In all submodules a package, it is necessary with an inlet module, the module entry is derived as the target object is exported package . For example, the following directory structure.

- / Home / User / lib / 
    - cat / 
        head.js 
        body.js 
        main.js 

// wherein cat catalog defines a package, which includes three sub-modules.
// main.js as an inlet module, which reads as follows: 
var head = the require ( ' ./head ' );
 var body = the require ( ' ./body ' ); 

exports.create = function (name) {
     return { 
        name: name, 
        head: head.create (), 
        body: body.create () 
    }; 
};

  When using other modules in the package, the package need to load the module inlet. Then the example above, use require('/home/user/lib/cat/main')can achieve the purpose, but the entrance module name appears in the path looks not a good idea. So we need to do extra work to make the package more like to use a single module.

1、index.js

  当模块的文件名是index.js,加载模块时可以使用模块所在目录的路径代替模块文件路径,因此接着上例,以下两条语句等价。

var cat = require('/home/user/lib/cat');
var cat = require('/home/user/lib/cat/index');

  这样处理后,就只需要把包目录路径传递给require函数,感觉上整个目录被当作单个模块使用,更有整体感。

2、package.json

  如果想自定义入口模块的文件名和存放位置,就需要在包目录下包含一个package.json文件,并在其中指定入口模块的路径。上例中的cat模块可以重构如下。

- /home/user/lib/
    - cat/
        + doc/
        - lib/
            head.js
            body.js
            main.js
        + tests/
        package.json

  其中package.json内容如下。

{
    "name": "cat",
    "main": "./lib/main.js"
}

  如此一来,就同样可以使用require('/home/user/lib/cat')的方式加载模块。NodeJS会根据包目录下的package.json找到入口模块所在位置

三、NPM

  NPM是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,常见的使用场景有以下几种:

  • 允许用户从NPM服务器下载别人编写的三方包到本地使用。

  • 允许用户从NPM服务器下载并安装别人编写的命令行程序到本地使用。

  • 允许用户将自己编写的包或命令行程序上传到NPM服务器供别人使用。

  可以看到,NPM建立了一个NodeJS生态圈,NodeJS开发者和用户可以在里边互通有无。以下分别介绍这三种场景下怎样使用NPM。

  npm install 包名,可以在包名后边加上@<version>来下载指定版本

  NPM对package.json的字段做了扩展,允许在其中申明三方包依赖

1、npm发布代码

  第一次使用NPM发布代码前需要注册一个账号。终端下运行npm adduser,之后按照提示做即可。账号搞定后,接着我们需要编辑package.json文件,加入NPM必需的字段。接着上边node-echo的例子,package.json里必要的字段如下。

{
    "name": "node-echo",           # 包名,在NPM服务器上须要保持唯一
    "version": "1.0.0",            # 当前版本号
    "dependencies": {              # 三方包依赖,需要指定包名和版本号
        "argv": "0.0.2"
      },
    "main": "./lib/echo.js",       # 入口模块位置
    "bin" : {
        "node-echo": "./bin/node-echo"      # 命令行程序名和主模块位置
    }
}

  之后,我们就可以在package.json所在目录下运行npm publish发布代码了。

2、这里再介绍一些NPM常用命令。

  • NPM提供了很多命令,例如installpublish,使用npm help可查看所有命令。

  • 使用npm help <command>可查看某条命令的详细帮助,例如npm help install

  • package.json所在目录下使用npm install . -g可先在本地安装当前命令行程序,可用于发布前的本地测试。

  • 使用npm update <package>可以把当前目录下node_modules子目录里边的对应模块更新至最新版本。

  • 使用npm update <package> -g可以把全局安装的对应命令行程序更新至最新版。

  • 使用npm cache clear可以清空NPM本地缓存,用于对付使用相同版本号发布新版本代码的人。

  • 使用npm unpublish <package>@<version>可以撤销发布自己发布过的某个版本代码。

小结:

  • 编写代码前先规划好目录结构,才能做到有条不紊。

  • 稍大些的程序可以将代码拆分为多个模块管理,更大些的程序可以使用包来组织模块。

  • 合理使用node_modulesNODE_PATH来解耦包的使用方式和物理路径。

  • 使用NPM加入NodeJS生态圈互通有无。

  • 想到了心仪的包名时请提前在NPM上抢注。

 

Guess you like

Origin www.cnblogs.com/goloving/p/11415656.html