这篇翻译不完整。请帮忙从英语翻译这篇文章

现在你知道什么是 Express,我们将向您展示如何在 Windows、Linux(Ubuntu)和Mac OS X 设置 Node/Express 的开发和测试环境。无论你使用那款常见的操作系统,这篇文章都会教你开发 Express 程序所需的知识。

预备: 知道如何打开终端/命令行。知道如何在你的开发计算机的操作系统上安装软件包。
目标: 在您的计算机上为 Express(x.xx) 建立一个开发环境。

Express 开发环境概述

Node 和 Express 可以让你很容易地在你的计算机上开始开发web应用程序。本节提供了所需工具的概述,解释了在Ubuntu、Mac OS X和Windows上安装Node(和Express)的一些最简单的方法,并展示了如何测试安装是否成功。

什么是 Express 开发环境?

Express开发环境包括安装在你本地计算机上的 Nodejs,NPM 包管理器和 Express 框架生成器(可选)。

Node and the NPM package manager are installed together from preprepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

NPM也可以在全局安装Express 应用生成器,这是一个用来创建遵循MVC模式的Express应用结构的工具。这个应用生成器是可选的,因为你不需要这个工具就可以创建一个Express应用,或者是构建一个拥有相同架构布局的Express应用。我们将会使用应用生成器,因为它会让初学者更容易上手,同时也会促进一个模块化的应用结构。

注意: 不像其他的互联网应用框架,这里的开发环境不包括一个单独的服务器.使用Node/Express的web应用创建并运行自己的web服务器!

在一个典型的开发环境中还需要一些其它的工具,包括文本编辑器,或者是集成开发环境来编写代码,还有诸如git这样的版本控制工具来安全地管理你不同版本的代码。我们假定你已经安装了这些工具(尤其是一个文本编辑器)。

支持什么操作系统?

Node可以运行在windows,macOS,Linux的许多分支,Docker等。几乎所有的个人电脑都可以有足够的性能在开发中运行node。Express运行在node环境中,所以所有可以运行node的平台都可以运行Express应用。

在这篇文章中,我们将会介绍如何在windows,macOS,Ubuntu Linux上进行安装。

你应该选择Node/Express的哪个版本?

 releases of Node 这里有许多个Node的发行版本,— 新的版本包含着bug的修复,对ECMAScript新标准的更多支持,以及针对Node APIs的改进。

通常你应该选择最新的LTS版本,因为它比“Current”版本更加稳定,"Current"版本包含最新的特性(这些特性仍旧在被维护中)。如果你需要的特性在LTS版本中没有提供,那么你可以去选择使用“Current”版本

对于Express而言,你应该总是使用最新版本。

数据库和其它依赖又该如何选择呢?

其它依赖,例如数据库驱动,模板引擎,身份认证引擎,等。它们是应用的一部分,使用NPM 包管理工具将它们引入到应用的环境中。我们将会在稍后的文章中对它们进行讨论。

安装 Node

为了使用Express你应该首先在你的操作系统上安装Nodejs和NPM。接下来的单元将会为你介绍在 Ubuntu Linux 16.04, Mac OS X, and Windows 10上安装LTS版本的Nodejs最简单的方法。.

Tip: 这部分内容将会为你介绍使用最简单的方法在我们的目标平台上安装Node和NPM,如果你使用其它的操作系统,或者你想了解更多的安装方法,你可以看一看链接的这篇文章 Installing Node.js via package manager (nodejs.org).

Windows and Mac OS X

I在windows和macOS上安装Node和NPM是非常容易的,因为你可以使用提供的安装包:

  1. 下载安装包:
    1. 访问 https://nodejs.org/en/
    2. 选择Download按钮下载LTS版本的Nodejs,推荐大多数用户去下载这个版本。
  2. 双击运行安装包,跟随安装提示进行安装。

Ubuntu 16.04

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

Warning: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

测试一下你的Nodejs和NPM是否安装成功

检查你是否成功安装node的最简单的方式就是在你的终端中使用“version”命令,检查一下是否成功返回了版本号:

>node -v
v8.9.1

Nodejs NPM包管理工具应该也被成功安装了,你可以使用同样的方式来测试一下:

>npm -v
5.6.0

下面激动人心的时刻到了,让我们使用原生代码来创建一个最基础的服务器,当你在浏览器中访问正确的url地址时,它将会在浏览器上简单的打印"Hello world":

  1. 将下面的代码复制到一个名为hellonode.js的文件中。在这使用了纯Node的特性(与Express无关)和一些ES6的语法:
    //Load HTTP module
    var http = require("http");
    
    //Create HTTP server and listen on port 8000 for requests
    http.createServer(function (request, response) {
    
       // Set the response HTTP header with HTTP status and Content type
       response.writeHead(200, {'Content-Type': 'text/plain'});
       
       // Send the response body "Hello World"
       response.end('Hello World\n');
    }).listen(8000);
    
    // Print URL for accessing server
    console.log('Server running at http://127.0.0.1:8000/')
    

         代码中导入了“http”模块,并且使用createServer()函数创建了一个服务器,该服务器会监听来自3000端口的HTTP请求。之后会在终端中打印一条信息,它将会告诉你可以访问哪一个url来测试该服务器。createServer()函数接受一个回调函数作为参数,这个回调函数将会在收到HTTP请求后进行调用。——它简单地返回了200“OK”状态码,和“Hello World”文本。

  1. Note:  如果你现在没办法搞清楚这些代码到底都做了哪些事情的话请不要担心,当我们开始使用Express的时候我们将会对它进行更加详细的解释。

  2. 在命令行工具中进入hellonode.js文件的目录,使用node +文件名的方式运行该脚本文件:
    >node hellonode.js
    Server running at http://127.0.0.1:8000/
    
  3. 在浏览器中输入这个URL (http://127.0.0.1:8000/)。如果一切正常运转,浏览器应该显示出“Hello,world”字符串。(译者注:输入localhost:8000也可以。)

Using NPM

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

注意: 从Node的角度来看,Express只是一个你要用NPM安装、在自己的代码中使用的包而已。

你可以手动用NPM一个个安装需要的包。但我们通常用一个纯文本文件--package.json--来管理依赖关系(译者注:也就是需要什么包)。This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

Adding dependencies

接下来的文章向你展示了如何通过NPM下载一个包,将其保存进项目的依赖中,以及如何在Node应用中使用它。

注意: 这里我们指定了用来获取和安装Express包的指令。过一会我们会展示为什么当我们使用Express应用生成器时,这个包(以及其他的包)已经为我们准备好了。This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

  1. First create a directory for your new application and navigate into it:
    mkdir myapp
    cd myapp
  2. Use the npm "init" command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults:
    npm init

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    {
      "name": "myapp",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
    
  3. Now install the Express library in the myapp directory. The package will automatically be saved to the dependencies list in your package.json file.
    npm install express

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    {
      "name": "myapp",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2"
      }
    }
    
  4. To use the library you call the require() function as shown below.
    var express = require('express')
    var app = express()
    
    app.get('/', function (req, res) {
      res.send('Hello World!')
    })
    
    app.listen(8000, function () {
      console.log('Example app listening on port 8000!')
    })
    

    上面的代码展示了一个小小的“HelloWorld”Express web应用。它导入了“express”包并用它创造了一个监听8000号端口的服务器(app),并且在控制台打印了一条信息,解释你能用什么样的URL来测试这个服务器。The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 

    Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

  5. You can start the server by calling node with the script in your command prompt:
    >node index.js
    Example app listening on port 8000
    
  6. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".

Development dependencies

如果一个依赖只在开发过程中使用到,你就应该改把它保存为“开发依赖”(development dependencies) (这样使用你的包的人就不必再他们的应用中安装这些依赖). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

npm install eslint --save-dev

The following entry would then be added to your application's package.json:

  "devDependencies": {
    "eslint": "^4.12.1"
  }

Note: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

运行任务

除了在NPM中定义和获取依赖,你还可以在package.json中定义命名脚本,并且调用NPM的run-script命令来运行它们。

This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

Note: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

"scripts": {
  ...
  "lint": "eslint src/js"
  ...
}

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

We would then be able to run eslint using NPM by calling:

npm run-script lint
# OR (using the alias)
npm run lint

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

Installing the Express Application Generator

The Express Application Generator tool generates an Express application "skeleton". You can install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

npm install express-generator -g

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

express helloworld

Note: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

express --help

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

{
  "name": "helloworld",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.15.5",
    "jade": "~1.11.0",
    "morgan": "~1.9.0",
    "serve-favicon": "~2.4.5"
  }
}

Install all the dependencies for the helloworld app using NPM as shown:

cd helloworld
npm install

Then run the app (the commands are slightly different for Windows and Linux/Mac), as shown below:

# Run the helloworld on Windows
SET DEBUG=helloworld:* & npm start

# Run helloworld on Linux/Mac OS X
DEBUG=helloworld:* npm start

The DEBUG command creates useful logging, resulting in an output like that shown below.

>SET DEBUG=helloworld:* & npm start

> helloworld@0.0.0 start D:\Github\expresstests\helloworld
> node ./bin/www

  helloworld:server Listening on port 3000 +0ms

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

Express - Generated App Default Screen

We'll talk more about the generated app when we get to the article on generating a skeleton application.

總結

你現在有一個Node開發環境在你的電腦上運行,可以用來創造Express網頁應用。你也看到如何用NPM來加載 Express到一個應用中,以及看到如何使用Express應用產生器,創建應用,然後執行它們。

下一篇文章,我們開始跟著教程一步一步實作,使用這個開發環境與搭配工具,建立一個完整的網頁應用。

See also

 

In this module

 

文档标签和贡献者

此页面的贡献者: yijie_sun, yaoqtan, jianchao_xue, edgar-chen, BarryLiu1995
最后编辑者: yijie_sun,