现在你知道什么是 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 can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

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

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

What operating systems are supported?

Node can be run on Windows, Mac OS X, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

In this article we provide setup instructions for Windows, Mac OS X, and Ubuntu Linux.

What version of Node/Express should you use?

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

For Express you should always use the latest version.

What about databases and other dependencies?

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

Installing Node

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, Mac OS X, and Windows 10.

Tip: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

Windows and Mac OS X

Installing Node and NPM on Windows and Mac OS X is straightforward because you can just use the provided installer:

  1. Download the required installer:
    1. Go to https://nodejs.org/en/
    2. Select the button to download the LTS build that is "Recommended for most users".
  2. Install Node by double-clicking on the downloaded file and following the installation prompts.

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.

Testing your Nodejs and NPM installation

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

>node -v

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

>npm -v

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

  1. Copy the following text into a file named hellonode.js. This uses only Node features (not Express):
    //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');
    // Print URL for accessing server
    console.log('Server running at')

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 8000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    Note:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

  2. Start the server by calling node along with the script name in your command prompt:
    >node hellonode.js
    Server running at
  3. 在浏览器中输入这个URL (。如果一切正常运转,浏览器应该显示出“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


注意: 这里我们指定了用来获取和安装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 ( 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.



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 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



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