From ee778d6eea54935fd05022e0ba8c49456003381a Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:48:24 +0100 Subject: unslug ko: move --- .../development_environment/index.html | 399 ++++++++++++++++ .../express_nodejs/skeleton_website/index.html | 512 +++++++++++++++++++++ .../index.html" | 399 ---------------- .../index.html" | 512 --------------------- .../node_server_without_framework/index.html | 74 +++ 5 files changed, 985 insertions(+), 911 deletions(-) create mode 100644 files/ko/learn/server-side/express_nodejs/development_environment/index.html create mode 100644 files/ko/learn/server-side/express_nodejs/skeleton_website/index.html delete mode 100644 "files/ko/learn/server-side/express_nodejs/\352\260\234\353\260\234_\355\231\230\352\262\275/index.html" delete mode 100644 "files/ko/learn/server-side/express_nodejs/\354\212\244\354\274\210\353\240\210\355\206\244_\354\233\271\354\202\254\354\235\264\355\212\270/index.html" create mode 100644 files/ko/learn/server-side/node_server_without_framework/index.html (limited to 'files/ko/learn/server-side') diff --git a/files/ko/learn/server-side/express_nodejs/development_environment/index.html b/files/ko/learn/server-side/express_nodejs/development_environment/index.html new file mode 100644 index 0000000000..f3ab1846f6 --- /dev/null +++ b/files/ko/learn/server-side/express_nodejs/development_environment/index.html @@ -0,0 +1,399 @@ +--- +title: Node 개발 환경을 설치하기 +slug: Learn/Server-side/Express_Nodejs/개발_환경 +tags: + - CodingScripting + - Express + - Node + - nodejs + - npm + - 개발 환경 + - 배움 + - 서버-사이드 + - 인트로 + - 초보자 +translation_of: Learn/Server-side/Express_Nodejs/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
+ +

이제 Express에 관한 내용을 알았으니, Windows, Linux (Ubuntu), 그리고 macOS 에서의 Node/Express 개발 환경을 설정하고 테스트하는 법을 보여드리겠습니다. 사용중인 운영 체제가 무엇이든 간에, 이 글은 당신에게 Express 앱 개발을 시작할 수 있도록 필요한 내용을 제공합니다.

+ + + + + + + + + + + + +
전제 조건:터미널 혹은 명령어 창을 여는 방법. 당신의 개발 컴퓨터의 운영 체제에 소프트웨어 패키지를 설치하는 방법을 알고 있어야 합니다.
목표:당신의 컴퓨터에 Express (X.XX) 을 위한 개발 환경을 설치하는 것.
+ +

Express 개발 환경 개요

+ +

Node와 Express를 통해 웹앱 개발을 한결 수월하게 할 수 있습니다. 이 섹션에서는 어떤 도구들이 필요한지, Ubuntu, macOS, 그리고 Windows에서 어떻게 Node와 Express를 설치하는지, 마지막으로, 설치 후 어떻게 테스트해볼 수 있는지 살펴볼 것입니다.

+ +

Express 개발 환경이란 무엇입니까?

+ +

Express개발환경은 Nodejs의 설치, NPM 패키지 매니저, 그리고 (선택적) 로컬 컴퓨터의 Express Application Generator 포함합니다.

+ +

Node and the NPM package manager are installed together from prepared 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.

+ +
+

Note: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

+
+ +

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, macOS, 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.

+ +

이 기사에서는 Windows, macOS, 그리고 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.

+ +

Node 설치하기

+ +

Express 를 사용하기 위해서 우선 운영체제에 Nodejs와 Node Package Manager (NPM)를 설치해야 합니다. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, 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 macOS

+ +

Node와 NPM을 설치하는 것은 간단합니다:

+ +
    +
  1. Installer를 다운받읍시다: +
      +
    1. https://nodejs.org/en/
    2. +
    3. "안정적이고 신뢰도가 높은" LTS버튼을 클릭해 다운로드를 시작합니다. .
    4. +
    +
  2. +
  3. 다운로드된 파일을 더블클릭해 Node를 설치합니다.
  4. +
+ +

The easiest way to install the most recent LTS version of Node 10.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_10.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 테스팅

+ +

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
+v10.15.1
+ +

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

+ +
>npm -v
+6.4.1
+ +

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 pure Node features (nothing from Express) and some ES6 syntax: + +
    //Load HTTP module
    +const http = require("http");
    +const hostname = '127.0.0.1';
    +const port = 3000;
    +
    +//Create HTTP server and listen on port 3000 for requests
    +const server = http.createServer((req, res) => {
    +
    +  //Set the response HTTP header with HTTP status and Content type
    +  res.statusCode = 200;
    +  res.setHeader('Content-Type', 'text/plain');
    +  res.end('Hello World\n');
    +});
    +
    +//listen for request on port 3000, and as a callback function have the port listened on logged
    +server.listen(port, hostname, () => {
    +  console.log(`Server running at http://${hostname}:${port}/`);
    +});
    +
    + +

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. 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. +
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: +
    >node hellonode.js
    +Server running at http://127.0.0.1:3000/
    +
    +
  4. +
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. +
+ +

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. 

+ +
+

Note: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

+
+ +

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named 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).

+ +

dependencies 추가

+ +

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

+ +
+

Note: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. 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. +
  3. 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"
    +}
    +
    +
  4. +
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. +
  7. +
    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.4"
    +  }
    +}
    +
    +
  8. +
  9. To use the Express library you call the require() function in your index.js file to include it in your application. Create this file now, in the root of the "myapp" application directory, and give it the following contents: +
    const express = require('express')
    +const app = express();
    +
    +app.get('/', (req, res) => {
    +  res.send('Hello World!')
    +});
    +
    +app.listen(8000, () => {
    +  console.log('Example app listening on port 8000!')
    +});
    +
    + +

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module using require() and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. 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.

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

Development dependencies

+ +

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). 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.

+
+ +

Running tasks

+ +

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. 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". 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": {
+    "cookie-parser": "~1.4.3",
+    "debug": "~2.6.9",
+    "express": "~4.16.0",
+    "http-errors": "~1.6.2",
+    "jade": "~1.11.0",
+    "morgan": "~1.9.0"
+  }
+}
+
+ + +
+ +

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/macOS), as shown below:

+ +
# Run the helloworld on Windows with Command Prompt
+SET DEBUG=helloworld:* & npm start
+
+# Run the helloworld on Windows with PowerShell
+SET DEBUG=helloworld:* | npm start
+
+# Run helloworld on Linux/macOS
+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.

+ + + +

Summary

+ +

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

+ +

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

+ + + +

In this module

+ + diff --git a/files/ko/learn/server-side/express_nodejs/skeleton_website/index.html b/files/ko/learn/server-side/express_nodejs/skeleton_website/index.html new file mode 100644 index 0000000000..ca72e39124 --- /dev/null +++ b/files/ko/learn/server-side/express_nodejs/skeleton_website/index.html @@ -0,0 +1,512 @@ +--- +title: 'Express Tutorial Part 2: 스켈레톤 웹사이트 만들기' +slug: Learn/Server-side/Express_Nodejs/스켈레톤_웹사이트 +translation_of: Learn/Server-side/Express_Nodejs/skeleton_website +--- +
{{LearnSidebar}}
+ +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}

+ +

This second article in our Express Tutorial shows how you can create a "skeleton" website project which you can then go on to populate with site-specific routes, templates/views, and database calls.

+ + + + + + + + + + + + +
Prerequisites:Set up a Node development environment. Review the Express Tutorial.
Objective:Express 앱 제너레이터를 사용하여 자신만의 새로운 웹사이트 프로젝트를 시작할 수 있다.
+ +

Overview

+ +

이 아티클은 당신이 Express Application Generator 도구를 이용하여 스켈레톤(최소한의 프레임 모형만 갖춘) 웹사이트를 만드는 방법을 보여줍니다. 이는 사이트에 맞춘 라우트, 뷰/템플릿 그리고 데이터 베이스를 사용할 수 있게 합니다. In this case, we'll use the tool to create the framework for our Local Library website, to which we'll later add all the other code needed by the site. The process is extremely simple, requiring only that you invoke the generator on the command line with a new project name, optionally also specifying the site's template engine and CSS generator.

+ +

The following sections show you how to call the application generator, and provides a little explanation about the different view/CSS options. We'll also explain how the skeleton website is structured. At the end, we'll show how you can run the website to verify that it works.

+ +
+

Note: The Express Application Generator is not the only generator for Express applications, and the generated project is not the only viable way to structure your files and directories. The generated site does however have a modular structure that is easy to extend and understand. For information about a minimal Express application, see Hello world example (Express docs).

+
+ +

Using the application generator

+ +

You should already have installed the generator as part of setting up a Node development environment. As a quick reminder, you install the generator tool site-wide using the NPM package manager, as shown:

+ +
npm install express-generator -g
+ +

The generator has a number of options, which you can view on the command line using the --help (or -h) command:

+ +
> express --help
+
+    Usage: express [options] [dir]
+
+
+  Options:
+
+        --version        output the version number
+    -e, --ejs            add ejs engine support
+        --pug            add pug engine support
+        --hbs            add handlebars engine support
+    -H, --hogan          add hogan.js engine support
+    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
+        --no-view        use static html instead of view engine
+    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
+        --git            add .gitignore
+    -f, --force          force on non-empty directory
+    -h, --help           output usage information
+
+ +

You can simply specify express to create a project inside the current directory using the Jade view engine and plain CSS (if you specify a directory name then the project will be created in a sub-folder with that name).

+ +
express
+ +

You can also choose a view (template) engine using --view and/or a CSS generation engine using --css.

+ +
+

Note: The other options for choosing template engines (e.g. --hogan, --ejs, --hbs etc.) are deprecated. Use --view (or -v)!

+
+ +

What view engine should I use?

+ +

The Express Application Generator allows you to configure a number of popular view/templating engines, including EJS, Hbs, Pug (Jade), Twig, and Vash, although it chooses Jade by default if you don't specify a view option. Express itself can also support a large number of other templating languages out of the box.

+ +
+

Note: If you want to use a template engine that isn't supported by the generator then see Using template engines with Express (Express docs) and the documentation for your target view engine.

+
+ +

Generally speaking, you should select a templating engine that delivers all the functionality you need and allows you to be productive sooner — or in other words, in the same way that you choose any other component! Some of the things to consider when comparing template engines:

+ + + +
+

Tip: There are many resources on the Internet to help you compare the different options!

+
+ +

For this project, we'll use the Pug templating engine (this is the recently-renamed Jade engine), as this is one of the most popular Express/JavaScript templating languages and is supported out of the box by the generator.

+ +

What CSS stylesheet engine should I use?

+ +

The Express Application Generator allows you to create a project that is configured to use the most common CSS stylesheet engines: LESS, SASS, Compass, Stylus.

+ +
+

Note: CSS has some limitations that make certain tasks difficult. CSS stylesheet engines allow you to use more powerful syntax for defining your CSS and then compile the definition into plain-old CSS for browsers to use.

+
+ +

As with templating engines, you should use the stylesheet engine that will allow your team to be most productive. For this project, we'll use the ordinary CSS (the default) as our CSS requirements are not sufficiently complicated to justify using anything else.

+ +

What database should I use?

+ +

The generated code doesn't use/include any databases. Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behavior/requirements for database management).

+ +

We'll discuss how to integrate with a database in a later article.

+ +

Creating the project

+ +

Local Library 샘플 앱을 위해서 우리는 express-locallibrary-tutorial 라는 이름의 프로젝트를 생성할 것입니다. Pug 라는(jade의 후속격) 템플릿 라이브러리를 사용할 것이며, CSS stylesheet 엔진은 사용하지 않습니다.

+ +

First, navigate to where you want to create the project and then run the Express Application Generator in the command prompt as shown:

+ +
express express-locallibrary-tutorial --view=pug
+
+ +

The generator will create (and list) the project's files.

+ +
   create : express-locallibrary-tutorial\
+   create : express-locallibrary-tutorial\public\
+   create : express-locallibrary-tutorial\public\javascripts\
+   create : express-locallibrary-tutorial\public\images\
+   create : express-locallibrary-tutorial\public\stylesheets\
+   create : express-locallibrary-tutorial\public\stylesheets\style.css
+   create : express-locallibrary-tutorial\routes\
+   create : express-locallibrary-tutorial\routes\index.js
+   create : express-locallibrary-tutorial\routes\users.js
+   create : express-locallibrary-tutorial\views\
+   create : express-locallibrary-tutorial\views\error.pug
+   create : express-locallibrary-tutorial\views\index.pug
+   create : express-locallibrary-tutorial\views\layout.pug
+   create : express-locallibrary-tutorial\app.js
+   create : express-locallibrary-tutorial\package.json
+   create : express-locallibrary-tutorial\bin\
+   create : express-locallibrary-tutorial\bin\www
+
+   change directory:
+     > cd express-locallibrary-tutorial
+
+   install dependencies:
+     > npm install
+
+   run the app:
+     > SET DEBUG=express-locallibrary-tutorial:* & npm start
+ +

At the end of the output, the generator provides instructions on how you install the dependencies (as listed in the package.json file) and then how to run the application (the instructions above are for Windows; on Linux/macOS they will be slightly different).

+ +
+

Note: When using Windows, the && and & assumes you are using the Command Prompt. If you are using the new default PowerShell terminal do not concatenate the commands with && and &. Instead set the DEBUG environment variable with $ENV:DEBUG = "express-locallibrary-tutorial:*";. The npm start can be followed by the npm start. 

+
+ +

Running the skeleton website

+ +

At this point, we have a complete skeleton project. The website doesn't actually do very much yet, but it's worth running it to show how it works.

+ +
    +
  1. First, install the dependencies (the install command will fetch all the dependency packages listed in the project's package.json file). + +
    cd express-locallibrary-tutorial
    +npm install
    +
  2. +
  3. Then run the application. +
      +
    • On Windows, use this command: +
      SET DEBUG=express-locallibrary-tutorial:* & npm start
      +
    • +
    • On macOS or Linux, use this command: +
      DEBUG=express-locallibrary-tutorial:* npm start
      +
      +
    • +
    +
  4. +
  5. Then load http://localhost:3000/ in your browser to access the app.
  6. +
+ +

You should see a browser page that looks like this:

+ +

Browser for default Express app generator website

+ +

You have a working Express application, serving itself to localhost:3000.

+ +
+

Note: You could also start the app just using the npm start command. Specifying the DEBUG variable as shown enables console logging/debugging. For example, when you visit the above page you'll see debug output like this:

+ +
>SET DEBUG=express-locallibrary-tutorial:* & npm start
+
+> express-locallibrary-tutorial@0.0.0 start D:\github\mdn\test\exprgen\express-locallibrary-tutorial
+> node ./bin/www
+
+  express-locallibrary-tutorial:server Listening on port 3000 +0ms
+GET / 304 490.296 ms - -
+GET /stylesheets/style.css 200 4.886 ms - 111
+
+
+ +

Enable server restart on file changes

+ +

Any changes you make to your Express website are currently not visible until you restart the server. It quickly becomes very irritating to have to stop and restart your server every time you make a change, so it is worth taking the time to automate restarting the server when needed.

+ +

One of the easiest such tools for this purpose is nodemon. This is usually installed globally (as it is a "tool"), but here we'll install and use it locally as a developer dependency, so that any developers working with the project get it automatically when they install the application. Use the following command in the root directory for the skeleton project:

+ +
npm install --save-dev nodemon
+ +

If you still choose to install nodemon globally to your machine, and not only to your project's package.json file:

+ +
npm install -g nodemon
+ +

If you open your project's package.json file you'll now see a new section with this dependency:

+ +
 "devDependencies": {
+    "nodemon": "^1.18.10"
+}
+
+ +

Because the tool isn't installed globally we can't launch it from the command line (unless we add it to the path) but we can call it from an NPM script because NPM knows all about the installed packages. Find the the scripts section of your package.json. Initially, it will contain one line, which begins with "start". Update it by putting a comma at the end of that line, and adding the "devstart" line seen below:

+ +
  "scripts": {
+    "start": "node ./bin/www",
+    "devstart": "nodemon ./bin/www",
+    "serverstart": "DEBUG=express-locallibrary-tutorial:* npm run devstart"
+  },
+
+ +

We can now start the server in almost exactly the same way as previously, but with the devstart command specified:

+ + + +
+

Note: Now if you edit any file in the project the server will restart (or you can restart it by typing rs on the command prompt at any time). You will still need to reload the browser to refresh the page.

+ +

We now have to call "npm run <scriptname>" rather than just npm start, because "start" is actually an NPM command that is mapped to the named script. We could have replaced the command in the start script but we only want to use nodemon during development, so it makes sense to create a new script command.

+ +

The serverstart command added to the scripts in the package.json above is a very good example. Using this approach means you no longer have to type a long command shown to start the server. Note that the particular command added to the script works for macOS or Linux only.

+
+ +

The generated project

+ +

Let's now take a look at the project we just created.

+ +

Directory structure

+ +

The generated project, now that you have installed dependencies, has the following file structure (files are the items not prefixed with "/"). The package.json file defines the application dependencies and other information. It also defines a startup script that will call the application entry point, the JavaScript file /bin/www. This sets up some of the application error handling and then loads app.js to do the rest of the work. The app routes are stored in separate modules under the routes/ directory. The templates are stored under the /views directory.

+ +
/express-locallibrary-tutorial
+    app.js
+    /bin
+        www
+    package.json
+    package-lock.json
+    /node_modules
+        [about 6700 subdirectories and files]
+    /public
+        /images
+        /javascripts
+        /stylesheets
+            style.css
+    /routes
+        index.jsusers.js
+    /views
+        error.pug
+        index.puglayout.pug
+
+
+ +

The following sections describe the files in a little more detail.

+ +

package.json

+ +

The package.json file defines the application dependencies and other information:

+ +
{
+  "name": "express-locallibrary-tutorial",
+  "version": "0.0.0",
+  "private": true,
+  "scripts": {
+    "start": "node ./bin/www",
+    "devstart": "nodemon ./bin/www"
+  },
+  "dependencies": {
+    "cookie-parser": "~1.4.3",
+    "debug": "~2.6.9",
+    "express": "~4.16.0",
+    "http-errors": "~1.6.2",
+    "morgan": "~1.9.0",
+    "pug": "2.0.0-beta11"
+  },
+  "devDependencies": {
+    "nodemon": "^1.18.10"
+  }
+}
+
+ +

The dependencies include the express package and the package for our selected view engine (pug). In addition, we have the following packages that are useful in many web applications:

+ + + +

The scripts section defines a "start" script, which is what we are invoking when we call npm start to start the server. From the script definition, you can see that this actually starts the JavaScript file ./bin/www with node. It also defines a "devstart" script, which we invoke when calling npm run devstart instead. This starts the same ./bin/www file, but with nodemon rather than node.

+ +
  "scripts": {
+    "start": "node ./bin/www",
+    "devstart": "nodemon ./bin/www"
+  },
+
+ +

www file

+ +

The file /bin/www is the application entry point! The very first thing this does is require() the "real" application entry point (app.js, in the project root) that sets up and returns the express() application object.

+ +
#!/usr/bin/env node
+
+/**
+ * Module dependencies.
+ */
+
+var app = require('../app');
+
+ +
+

Note: require() is a global node function that is used to import modules into the current file. Here we specify app.js module using a relative path and omitting the optional (.js) file extension.

+
+ +

The remainder of the code in this file sets up a node HTTP server with app set to a specific port (defined in an environment variable or 3000 if the variable isn't defined), and starts listening and reporting server errors and connections. For now you don't really need to know anything else about the code (everything in this file is "boilerplate"), but feel free to review it if you're interested.

+ +

app.js

+ +

This file creates an express application object (named app, by convention), sets up the application with various settings and middleware, and then exports the app from the module. The code below shows just the parts of the file that create and export the app object:

+ +
var express = require('express');
+var app = express();
+...
+module.exports = app;
+
+ +

Back in the www entry point file above, it is this module.exports object that is supplied to the caller when this file is imported.

+ +

Let's work through the app.js file in detail. First, we import some useful node libraries into the file using require(), including http-errors, expressmorgan and cookie-parser that we previously downloaded for our application using NPM; and path, which is a core Node library for parsing file and directory paths.

+ +
var createError = require('http-errors');
+var express = require('express');
+var path = require('path');
+var cookieParser = require('cookie-parser');
+var logger = require('morgan');
+
+ +

Then we require() modules from our routes directory. These modules/files contain code for handling particular sets of related "routes" (URL paths). When we extend the skeleton application, for example to list all books in the library, we will add a new file for dealing with book-related routes.

+ +
var indexRouter = require('./routes/index');
+var usersRouter = require('./routes/users');
+
+ +
+

Note: At this point, we have just imported the module; we haven't actually used its routes yet (this happens just a little bit further down the file).

+
+ +

Next, we create the app object using our imported express module, and then use it to set up the view (template) engine. There are two parts to setting up the engine. First, we set the 'views' value to specify the folder where the templates will be stored (in this case the subfolder /views). Then we set the 'view engine' value to specify the template library (in this case "pug").

+ +
var app = express();
+
+// view engine setup
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+
+ +

The next set of functions call app.use() to add the middleware libraries into the request handling chain. In addition to the 3rd party libraries we imported previously, we use the express.static middleware to get Express to serve all the static files in the /public directory in the project root.

+ +
app.use(logger('dev'));
+app.use(express.json());
+app.use(express.urlencoded({ extended: false }));
+app.use(cookieParser());
+app.use(express.static(path.join(__dirname, 'public')));
+
+ +

Now that all the other middleware is set up, we add our (previously imported) route-handling code to the request handling chain. The imported code will define particular routes for the different parts of the site:

+ +
app.use('/', indexRouter);
+app.use('/users', usersRouter);
+
+ +
+

Note: The paths specified above ('/' and '/users') are treated as a prefix to routes defined in the imported files. So for example, if the imported users module defines a route for /profile, you would access that route at /users/profile. We'll talk more about routes in a later article.

+
+ +

The last middleware in the file adds handler methods for errors and HTTP 404 responses.

+ +
// catch 404 and forward to error handler
+app.use(function(req, res, next) {
+  next(createError(404));
+});
+
+// error handler
+app.use(function(err, req, res, next) {
+  // set locals, only providing error in development
+  res.locals.message = err.message;
+  res.locals.error = req.app.get('env') === 'development' ? err : {};
+
+  // render the error page
+  res.status(err.status || 500);
+  res.render('error');
+});
+
+ +

The Express application object (app) is now fully configured. The last step is to add it to the module exports (this is what allows it to be imported by /bin/www).

+ +
module.exports = app;
+ +

Routes

+ +

The route file /routes/users.js is shown below (route files share a similar structure, so we don't need to also show index.js). First, it loads the express module and uses it to get an express.Router object. Then it specifies a route on that object and lastly exports the router from the module (this is what allows the file to be imported into app.js).

+ +
var express = require('express');
+var router = express.Router();
+
+/* GET users listing. */
+router.get('/', function(req, res, next) {
+  res.send('respond with a resource');
+});
+
+module.exports = router;
+
+ +

The route defines a callback that will be invoked whenever an HTTP GET request with the correct pattern is detected. The matching pattern is the route specified when the module is imported ('/users') plus whatever is defined in this file ('/'). In other words, this route will be used when an URL of /users/ is received.

+ +
+

Tip: Try this out by running the server with node and visiting the URL in your browser: http://localhost:3000/users/. You should see a message: 'respond with a resource'.

+
+ +

One thing of interest above is that the callback function has the third argument 'next', and is hence a middleware function rather than a simple route callback. While the code doesn't currently use the next argument, it may be useful in the future if you want to add multiple route handlers to the '/' route path.

+ +

Views (templates)

+ +

The views (templates) are stored in the /views directory (as specified in app.js) and are given the file extension .pug. The method Response.render() is used to render a specified template along with the values of named variables passed in an object, and then send the result as a response. In the code below from /routes/index.js you can see how that route renders a response using the template "index" passing the template variable "title".

+ +
/* GET home page. */
+router.get('/', function(req, res, next) {
+  res.render('index', { title: 'Express' });
+});
+
+ +

The corresponding template for the above route is given below (index.pug). We'll talk more about the syntax later. All you need to know for now is that the title variable (with value 'Express') is inserted where specified in the template.

+ +
extends layout
+
+block content
+  h1= title
+  p Welcome to #{title}
+
+ +

Challenge yourself

+ +

Create a new route in /routes/users.js that will display the text "You're so cool" at URL /users/cool/. Test it by running the server and visiting http://localhost:3000/users/cool/ in your browser

+ + + +

Summary

+ +

You have now created a skeleton website project for the Local Library and verified that it runs using node. Most importantly, you also understand how the project is structured, so you have a good idea where we need to make changes to add routes and views for our local library.

+ +

Next, we'll start modifying the skeleton so that it works as a library website.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}

+ +

In this module

+ + diff --git "a/files/ko/learn/server-side/express_nodejs/\352\260\234\353\260\234_\355\231\230\352\262\275/index.html" "b/files/ko/learn/server-side/express_nodejs/\352\260\234\353\260\234_\355\231\230\352\262\275/index.html" deleted file mode 100644 index f3ab1846f6..0000000000 --- "a/files/ko/learn/server-side/express_nodejs/\352\260\234\353\260\234_\355\231\230\352\262\275/index.html" +++ /dev/null @@ -1,399 +0,0 @@ ---- -title: Node 개발 환경을 설치하기 -slug: Learn/Server-side/Express_Nodejs/개발_환경 -tags: - - CodingScripting - - Express - - Node - - nodejs - - npm - - 개발 환경 - - 배움 - - 서버-사이드 - - 인트로 - - 초보자 -translation_of: Learn/Server-side/Express_Nodejs/development_environment ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
- -

이제 Express에 관한 내용을 알았으니, Windows, Linux (Ubuntu), 그리고 macOS 에서의 Node/Express 개발 환경을 설정하고 테스트하는 법을 보여드리겠습니다. 사용중인 운영 체제가 무엇이든 간에, 이 글은 당신에게 Express 앱 개발을 시작할 수 있도록 필요한 내용을 제공합니다.

- - - - - - - - - - - - -
전제 조건:터미널 혹은 명령어 창을 여는 방법. 당신의 개발 컴퓨터의 운영 체제에 소프트웨어 패키지를 설치하는 방법을 알고 있어야 합니다.
목표:당신의 컴퓨터에 Express (X.XX) 을 위한 개발 환경을 설치하는 것.
- -

Express 개발 환경 개요

- -

Node와 Express를 통해 웹앱 개발을 한결 수월하게 할 수 있습니다. 이 섹션에서는 어떤 도구들이 필요한지, Ubuntu, macOS, 그리고 Windows에서 어떻게 Node와 Express를 설치하는지, 마지막으로, 설치 후 어떻게 테스트해볼 수 있는지 살펴볼 것입니다.

- -

Express 개발 환경이란 무엇입니까?

- -

Express개발환경은 Nodejs의 설치, NPM 패키지 매니저, 그리고 (선택적) 로컬 컴퓨터의 Express Application Generator 포함합니다.

- -

Node and the NPM package manager are installed together from prepared 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.

- -
-

Note: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

-
- -

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, macOS, 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.

- -

이 기사에서는 Windows, macOS, 그리고 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.

- -

Node 설치하기

- -

Express 를 사용하기 위해서 우선 운영체제에 Nodejs와 Node Package Manager (NPM)를 설치해야 합니다. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, 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 macOS

- -

Node와 NPM을 설치하는 것은 간단합니다:

- -
    -
  1. Installer를 다운받읍시다: -
      -
    1. https://nodejs.org/en/
    2. -
    3. "안정적이고 신뢰도가 높은" LTS버튼을 클릭해 다운로드를 시작합니다. .
    4. -
    -
  2. -
  3. 다운로드된 파일을 더블클릭해 Node를 설치합니다.
  4. -
- -

The easiest way to install the most recent LTS version of Node 10.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_10.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 테스팅

- -

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
-v10.15.1
- -

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

- -
>npm -v
-6.4.1
- -

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 pure Node features (nothing from Express) and some ES6 syntax: - -
    //Load HTTP module
    -const http = require("http");
    -const hostname = '127.0.0.1';
    -const port = 3000;
    -
    -//Create HTTP server and listen on port 3000 for requests
    -const server = http.createServer((req, res) => {
    -
    -  //Set the response HTTP header with HTTP status and Content type
    -  res.statusCode = 200;
    -  res.setHeader('Content-Type', 'text/plain');
    -  res.end('Hello World\n');
    -});
    -
    -//listen for request on port 3000, and as a callback function have the port listened on logged
    -server.listen(port, hostname, () => {
    -  console.log(`Server running at http://${hostname}:${port}/`);
    -});
    -
    - -

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. 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. -
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: -
    >node hellonode.js
    -Server running at http://127.0.0.1:3000/
    -
    -
  4. -
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. -
- -

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. 

- -
-

Note: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

-
- -

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named 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).

- -

dependencies 추가

- -

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

- -
-

Note: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. 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. -
  3. 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"
    -}
    -
    -
  4. -
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. -
  7. -
    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.4"
    -  }
    -}
    -
    -
  8. -
  9. To use the Express library you call the require() function in your index.js file to include it in your application. Create this file now, in the root of the "myapp" application directory, and give it the following contents: -
    const express = require('express')
    -const app = express();
    -
    -app.get('/', (req, res) => {
    -  res.send('Hello World!')
    -});
    -
    -app.listen(8000, () => {
    -  console.log('Example app listening on port 8000!')
    -});
    -
    - -

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module using require() and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. 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.

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

Development dependencies

- -

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). 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.

-
- -

Running tasks

- -

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. 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". 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": {
-    "cookie-parser": "~1.4.3",
-    "debug": "~2.6.9",
-    "express": "~4.16.0",
-    "http-errors": "~1.6.2",
-    "jade": "~1.11.0",
-    "morgan": "~1.9.0"
-  }
-}
-
- - -
- -

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/macOS), as shown below:

- -
# Run the helloworld on Windows with Command Prompt
-SET DEBUG=helloworld:* & npm start
-
-# Run the helloworld on Windows with PowerShell
-SET DEBUG=helloworld:* | npm start
-
-# Run helloworld on Linux/macOS
-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.

- - - -

Summary

- -

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

- -

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

- - - -

In this module

- - diff --git "a/files/ko/learn/server-side/express_nodejs/\354\212\244\354\274\210\353\240\210\355\206\244_\354\233\271\354\202\254\354\235\264\355\212\270/index.html" "b/files/ko/learn/server-side/express_nodejs/\354\212\244\354\274\210\353\240\210\355\206\244_\354\233\271\354\202\254\354\235\264\355\212\270/index.html" deleted file mode 100644 index ca72e39124..0000000000 --- "a/files/ko/learn/server-side/express_nodejs/\354\212\244\354\274\210\353\240\210\355\206\244_\354\233\271\354\202\254\354\235\264\355\212\270/index.html" +++ /dev/null @@ -1,512 +0,0 @@ ---- -title: 'Express Tutorial Part 2: 스켈레톤 웹사이트 만들기' -slug: Learn/Server-side/Express_Nodejs/스켈레톤_웹사이트 -translation_of: Learn/Server-side/Express_Nodejs/skeleton_website ---- -
{{LearnSidebar}}
- -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}

- -

This second article in our Express Tutorial shows how you can create a "skeleton" website project which you can then go on to populate with site-specific routes, templates/views, and database calls.

- - - - - - - - - - - - -
Prerequisites:Set up a Node development environment. Review the Express Tutorial.
Objective:Express 앱 제너레이터를 사용하여 자신만의 새로운 웹사이트 프로젝트를 시작할 수 있다.
- -

Overview

- -

이 아티클은 당신이 Express Application Generator 도구를 이용하여 스켈레톤(최소한의 프레임 모형만 갖춘) 웹사이트를 만드는 방법을 보여줍니다. 이는 사이트에 맞춘 라우트, 뷰/템플릿 그리고 데이터 베이스를 사용할 수 있게 합니다. In this case, we'll use the tool to create the framework for our Local Library website, to which we'll later add all the other code needed by the site. The process is extremely simple, requiring only that you invoke the generator on the command line with a new project name, optionally also specifying the site's template engine and CSS generator.

- -

The following sections show you how to call the application generator, and provides a little explanation about the different view/CSS options. We'll also explain how the skeleton website is structured. At the end, we'll show how you can run the website to verify that it works.

- -
-

Note: The Express Application Generator is not the only generator for Express applications, and the generated project is not the only viable way to structure your files and directories. The generated site does however have a modular structure that is easy to extend and understand. For information about a minimal Express application, see Hello world example (Express docs).

-
- -

Using the application generator

- -

You should already have installed the generator as part of setting up a Node development environment. As a quick reminder, you install the generator tool site-wide using the NPM package manager, as shown:

- -
npm install express-generator -g
- -

The generator has a number of options, which you can view on the command line using the --help (or -h) command:

- -
> express --help
-
-    Usage: express [options] [dir]
-
-
-  Options:
-
-        --version        output the version number
-    -e, --ejs            add ejs engine support
-        --pug            add pug engine support
-        --hbs            add handlebars engine support
-    -H, --hogan          add hogan.js engine support
-    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-        --no-view        use static html instead of view engine
-    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
-        --git            add .gitignore
-    -f, --force          force on non-empty directory
-    -h, --help           output usage information
-
- -

You can simply specify express to create a project inside the current directory using the Jade view engine and plain CSS (if you specify a directory name then the project will be created in a sub-folder with that name).

- -
express
- -

You can also choose a view (template) engine using --view and/or a CSS generation engine using --css.

- -
-

Note: The other options for choosing template engines (e.g. --hogan, --ejs, --hbs etc.) are deprecated. Use --view (or -v)!

-
- -

What view engine should I use?

- -

The Express Application Generator allows you to configure a number of popular view/templating engines, including EJS, Hbs, Pug (Jade), Twig, and Vash, although it chooses Jade by default if you don't specify a view option. Express itself can also support a large number of other templating languages out of the box.

- -
-

Note: If you want to use a template engine that isn't supported by the generator then see Using template engines with Express (Express docs) and the documentation for your target view engine.

-
- -

Generally speaking, you should select a templating engine that delivers all the functionality you need and allows you to be productive sooner — or in other words, in the same way that you choose any other component! Some of the things to consider when comparing template engines:

- - - -
-

Tip: There are many resources on the Internet to help you compare the different options!

-
- -

For this project, we'll use the Pug templating engine (this is the recently-renamed Jade engine), as this is one of the most popular Express/JavaScript templating languages and is supported out of the box by the generator.

- -

What CSS stylesheet engine should I use?

- -

The Express Application Generator allows you to create a project that is configured to use the most common CSS stylesheet engines: LESS, SASS, Compass, Stylus.

- -
-

Note: CSS has some limitations that make certain tasks difficult. CSS stylesheet engines allow you to use more powerful syntax for defining your CSS and then compile the definition into plain-old CSS for browsers to use.

-
- -

As with templating engines, you should use the stylesheet engine that will allow your team to be most productive. For this project, we'll use the ordinary CSS (the default) as our CSS requirements are not sufficiently complicated to justify using anything else.

- -

What database should I use?

- -

The generated code doesn't use/include any databases. Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behavior/requirements for database management).

- -

We'll discuss how to integrate with a database in a later article.

- -

Creating the project

- -

Local Library 샘플 앱을 위해서 우리는 express-locallibrary-tutorial 라는 이름의 프로젝트를 생성할 것입니다. Pug 라는(jade의 후속격) 템플릿 라이브러리를 사용할 것이며, CSS stylesheet 엔진은 사용하지 않습니다.

- -

First, navigate to where you want to create the project and then run the Express Application Generator in the command prompt as shown:

- -
express express-locallibrary-tutorial --view=pug
-
- -

The generator will create (and list) the project's files.

- -
   create : express-locallibrary-tutorial\
-   create : express-locallibrary-tutorial\public\
-   create : express-locallibrary-tutorial\public\javascripts\
-   create : express-locallibrary-tutorial\public\images\
-   create : express-locallibrary-tutorial\public\stylesheets\
-   create : express-locallibrary-tutorial\public\stylesheets\style.css
-   create : express-locallibrary-tutorial\routes\
-   create : express-locallibrary-tutorial\routes\index.js
-   create : express-locallibrary-tutorial\routes\users.js
-   create : express-locallibrary-tutorial\views\
-   create : express-locallibrary-tutorial\views\error.pug
-   create : express-locallibrary-tutorial\views\index.pug
-   create : express-locallibrary-tutorial\views\layout.pug
-   create : express-locallibrary-tutorial\app.js
-   create : express-locallibrary-tutorial\package.json
-   create : express-locallibrary-tutorial\bin\
-   create : express-locallibrary-tutorial\bin\www
-
-   change directory:
-     > cd express-locallibrary-tutorial
-
-   install dependencies:
-     > npm install
-
-   run the app:
-     > SET DEBUG=express-locallibrary-tutorial:* & npm start
- -

At the end of the output, the generator provides instructions on how you install the dependencies (as listed in the package.json file) and then how to run the application (the instructions above are for Windows; on Linux/macOS they will be slightly different).

- -
-

Note: When using Windows, the && and & assumes you are using the Command Prompt. If you are using the new default PowerShell terminal do not concatenate the commands with && and &. Instead set the DEBUG environment variable with $ENV:DEBUG = "express-locallibrary-tutorial:*";. The npm start can be followed by the npm start. 

-
- -

Running the skeleton website

- -

At this point, we have a complete skeleton project. The website doesn't actually do very much yet, but it's worth running it to show how it works.

- -
    -
  1. First, install the dependencies (the install command will fetch all the dependency packages listed in the project's package.json file). - -
    cd express-locallibrary-tutorial
    -npm install
    -
  2. -
  3. Then run the application. -
      -
    • On Windows, use this command: -
      SET DEBUG=express-locallibrary-tutorial:* & npm start
      -
    • -
    • On macOS or Linux, use this command: -
      DEBUG=express-locallibrary-tutorial:* npm start
      -
      -
    • -
    -
  4. -
  5. Then load http://localhost:3000/ in your browser to access the app.
  6. -
- -

You should see a browser page that looks like this:

- -

Browser for default Express app generator website

- -

You have a working Express application, serving itself to localhost:3000.

- -
-

Note: You could also start the app just using the npm start command. Specifying the DEBUG variable as shown enables console logging/debugging. For example, when you visit the above page you'll see debug output like this:

- -
>SET DEBUG=express-locallibrary-tutorial:* & npm start
-
-> express-locallibrary-tutorial@0.0.0 start D:\github\mdn\test\exprgen\express-locallibrary-tutorial
-> node ./bin/www
-
-  express-locallibrary-tutorial:server Listening on port 3000 +0ms
-GET / 304 490.296 ms - -
-GET /stylesheets/style.css 200 4.886 ms - 111
-
-
- -

Enable server restart on file changes

- -

Any changes you make to your Express website are currently not visible until you restart the server. It quickly becomes very irritating to have to stop and restart your server every time you make a change, so it is worth taking the time to automate restarting the server when needed.

- -

One of the easiest such tools for this purpose is nodemon. This is usually installed globally (as it is a "tool"), but here we'll install and use it locally as a developer dependency, so that any developers working with the project get it automatically when they install the application. Use the following command in the root directory for the skeleton project:

- -
npm install --save-dev nodemon
- -

If you still choose to install nodemon globally to your machine, and not only to your project's package.json file:

- -
npm install -g nodemon
- -

If you open your project's package.json file you'll now see a new section with this dependency:

- -
 "devDependencies": {
-    "nodemon": "^1.18.10"
-}
-
- -

Because the tool isn't installed globally we can't launch it from the command line (unless we add it to the path) but we can call it from an NPM script because NPM knows all about the installed packages. Find the the scripts section of your package.json. Initially, it will contain one line, which begins with "start". Update it by putting a comma at the end of that line, and adding the "devstart" line seen below:

- -
  "scripts": {
-    "start": "node ./bin/www",
-    "devstart": "nodemon ./bin/www",
-    "serverstart": "DEBUG=express-locallibrary-tutorial:* npm run devstart"
-  },
-
- -

We can now start the server in almost exactly the same way as previously, but with the devstart command specified:

- - - -
-

Note: Now if you edit any file in the project the server will restart (or you can restart it by typing rs on the command prompt at any time). You will still need to reload the browser to refresh the page.

- -

We now have to call "npm run <scriptname>" rather than just npm start, because "start" is actually an NPM command that is mapped to the named script. We could have replaced the command in the start script but we only want to use nodemon during development, so it makes sense to create a new script command.

- -

The serverstart command added to the scripts in the package.json above is a very good example. Using this approach means you no longer have to type a long command shown to start the server. Note that the particular command added to the script works for macOS or Linux only.

-
- -

The generated project

- -

Let's now take a look at the project we just created.

- -

Directory structure

- -

The generated project, now that you have installed dependencies, has the following file structure (files are the items not prefixed with "/"). The package.json file defines the application dependencies and other information. It also defines a startup script that will call the application entry point, the JavaScript file /bin/www. This sets up some of the application error handling and then loads app.js to do the rest of the work. The app routes are stored in separate modules under the routes/ directory. The templates are stored under the /views directory.

- -
/express-locallibrary-tutorial
-    app.js
-    /bin
-        www
-    package.json
-    package-lock.json
-    /node_modules
-        [about 6700 subdirectories and files]
-    /public
-        /images
-        /javascripts
-        /stylesheets
-            style.css
-    /routes
-        index.jsusers.js
-    /views
-        error.pug
-        index.puglayout.pug
-
-
- -

The following sections describe the files in a little more detail.

- -

package.json

- -

The package.json file defines the application dependencies and other information:

- -
{
-  "name": "express-locallibrary-tutorial",
-  "version": "0.0.0",
-  "private": true,
-  "scripts": {
-    "start": "node ./bin/www",
-    "devstart": "nodemon ./bin/www"
-  },
-  "dependencies": {
-    "cookie-parser": "~1.4.3",
-    "debug": "~2.6.9",
-    "express": "~4.16.0",
-    "http-errors": "~1.6.2",
-    "morgan": "~1.9.0",
-    "pug": "2.0.0-beta11"
-  },
-  "devDependencies": {
-    "nodemon": "^1.18.10"
-  }
-}
-
- -

The dependencies include the express package and the package for our selected view engine (pug). In addition, we have the following packages that are useful in many web applications:

- - - -

The scripts section defines a "start" script, which is what we are invoking when we call npm start to start the server. From the script definition, you can see that this actually starts the JavaScript file ./bin/www with node. It also defines a "devstart" script, which we invoke when calling npm run devstart instead. This starts the same ./bin/www file, but with nodemon rather than node.

- -
  "scripts": {
-    "start": "node ./bin/www",
-    "devstart": "nodemon ./bin/www"
-  },
-
- -

www file

- -

The file /bin/www is the application entry point! The very first thing this does is require() the "real" application entry point (app.js, in the project root) that sets up and returns the express() application object.

- -
#!/usr/bin/env node
-
-/**
- * Module dependencies.
- */
-
-var app = require('../app');
-
- -
-

Note: require() is a global node function that is used to import modules into the current file. Here we specify app.js module using a relative path and omitting the optional (.js) file extension.

-
- -

The remainder of the code in this file sets up a node HTTP server with app set to a specific port (defined in an environment variable or 3000 if the variable isn't defined), and starts listening and reporting server errors and connections. For now you don't really need to know anything else about the code (everything in this file is "boilerplate"), but feel free to review it if you're interested.

- -

app.js

- -

This file creates an express application object (named app, by convention), sets up the application with various settings and middleware, and then exports the app from the module. The code below shows just the parts of the file that create and export the app object:

- -
var express = require('express');
-var app = express();
-...
-module.exports = app;
-
- -

Back in the www entry point file above, it is this module.exports object that is supplied to the caller when this file is imported.

- -

Let's work through the app.js file in detail. First, we import some useful node libraries into the file using require(), including http-errors, expressmorgan and cookie-parser that we previously downloaded for our application using NPM; and path, which is a core Node library for parsing file and directory paths.

- -
var createError = require('http-errors');
-var express = require('express');
-var path = require('path');
-var cookieParser = require('cookie-parser');
-var logger = require('morgan');
-
- -

Then we require() modules from our routes directory. These modules/files contain code for handling particular sets of related "routes" (URL paths). When we extend the skeleton application, for example to list all books in the library, we will add a new file for dealing with book-related routes.

- -
var indexRouter = require('./routes/index');
-var usersRouter = require('./routes/users');
-
- -
-

Note: At this point, we have just imported the module; we haven't actually used its routes yet (this happens just a little bit further down the file).

-
- -

Next, we create the app object using our imported express module, and then use it to set up the view (template) engine. There are two parts to setting up the engine. First, we set the 'views' value to specify the folder where the templates will be stored (in this case the subfolder /views). Then we set the 'view engine' value to specify the template library (in this case "pug").

- -
var app = express();
-
-// view engine setup
-app.set('views', path.join(__dirname, 'views'));
-app.set('view engine', 'pug');
-
- -

The next set of functions call app.use() to add the middleware libraries into the request handling chain. In addition to the 3rd party libraries we imported previously, we use the express.static middleware to get Express to serve all the static files in the /public directory in the project root.

- -
app.use(logger('dev'));
-app.use(express.json());
-app.use(express.urlencoded({ extended: false }));
-app.use(cookieParser());
-app.use(express.static(path.join(__dirname, 'public')));
-
- -

Now that all the other middleware is set up, we add our (previously imported) route-handling code to the request handling chain. The imported code will define particular routes for the different parts of the site:

- -
app.use('/', indexRouter);
-app.use('/users', usersRouter);
-
- -
-

Note: The paths specified above ('/' and '/users') are treated as a prefix to routes defined in the imported files. So for example, if the imported users module defines a route for /profile, you would access that route at /users/profile. We'll talk more about routes in a later article.

-
- -

The last middleware in the file adds handler methods for errors and HTTP 404 responses.

- -
// catch 404 and forward to error handler
-app.use(function(req, res, next) {
-  next(createError(404));
-});
-
-// error handler
-app.use(function(err, req, res, next) {
-  // set locals, only providing error in development
-  res.locals.message = err.message;
-  res.locals.error = req.app.get('env') === 'development' ? err : {};
-
-  // render the error page
-  res.status(err.status || 500);
-  res.render('error');
-});
-
- -

The Express application object (app) is now fully configured. The last step is to add it to the module exports (this is what allows it to be imported by /bin/www).

- -
module.exports = app;
- -

Routes

- -

The route file /routes/users.js is shown below (route files share a similar structure, so we don't need to also show index.js). First, it loads the express module and uses it to get an express.Router object. Then it specifies a route on that object and lastly exports the router from the module (this is what allows the file to be imported into app.js).

- -
var express = require('express');
-var router = express.Router();
-
-/* GET users listing. */
-router.get('/', function(req, res, next) {
-  res.send('respond with a resource');
-});
-
-module.exports = router;
-
- -

The route defines a callback that will be invoked whenever an HTTP GET request with the correct pattern is detected. The matching pattern is the route specified when the module is imported ('/users') plus whatever is defined in this file ('/'). In other words, this route will be used when an URL of /users/ is received.

- -
-

Tip: Try this out by running the server with node and visiting the URL in your browser: http://localhost:3000/users/. You should see a message: 'respond with a resource'.

-
- -

One thing of interest above is that the callback function has the third argument 'next', and is hence a middleware function rather than a simple route callback. While the code doesn't currently use the next argument, it may be useful in the future if you want to add multiple route handlers to the '/' route path.

- -

Views (templates)

- -

The views (templates) are stored in the /views directory (as specified in app.js) and are given the file extension .pug. The method Response.render() is used to render a specified template along with the values of named variables passed in an object, and then send the result as a response. In the code below from /routes/index.js you can see how that route renders a response using the template "index" passing the template variable "title".

- -
/* GET home page. */
-router.get('/', function(req, res, next) {
-  res.render('index', { title: 'Express' });
-});
-
- -

The corresponding template for the above route is given below (index.pug). We'll talk more about the syntax later. All you need to know for now is that the title variable (with value 'Express') is inserted where specified in the template.

- -
extends layout
-
-block content
-  h1= title
-  p Welcome to #{title}
-
- -

Challenge yourself

- -

Create a new route in /routes/users.js that will display the text "You're so cool" at URL /users/cool/. Test it by running the server and visiting http://localhost:3000/users/cool/ in your browser

- - - -

Summary

- -

You have now created a skeleton website project for the Local Library and verified that it runs using node. Most importantly, you also understand how the project is structured, so you have a good idea where we need to make changes to add routes and views for our local library.

- -

Next, we'll start modifying the skeleton so that it works as a library website.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}

- -

In this module

- - diff --git a/files/ko/learn/server-side/node_server_without_framework/index.html b/files/ko/learn/server-side/node_server_without_framework/index.html new file mode 100644 index 0000000000..1050f6aafd --- /dev/null +++ b/files/ko/learn/server-side/node_server_without_framework/index.html @@ -0,0 +1,74 @@ +--- +title: Node server without framework +slug: Node_server_without_framework +translation_of: Learn/Server-side/Node_server_without_framework +--- +

소개

+ +

물론 Node 는 서버를 만들고 실행하는데 도움을 주는 많은 프레임워크가 있습니다, 예를 들면:

+ + + +

하지만, 모든 것에 꼭 맞는 사이즈가 없듯이, 개발자들은 어떤 다른 의존성 없이 스스로 서버를 만들어야 할 때가 있습니다.

+ +

예제

+ +

다음은 짧고 간단한 정적 파일 nodejs 서버입니다.

+ +
var http = require('http');
+var fs = require('fs');
+var path = require('path');
+
+http.createServer(function (request, response) {
+    console.log('request ', request.url);
+
+    var filePath = '.' + request.url;
+    if (filePath == './')
+        filePath = './index.html';
+
+    var extname = String(path.extname(filePath)).toLowerCase();
+    var contentType = 'text/html';
+    var mimeTypes = {
+        '.html': 'text/html',
+        '.js': 'text/javascript',
+        '.css': 'text/css',
+        '.json': 'application/json',
+        '.png': 'image/png',
+        '.jpg': 'image/jpg',
+        '.gif': 'image/gif',
+        '.wav': 'audio/wav',
+        '.mp4': 'video/mp4',
+        '.woff': 'application/font-woff',
+        '.ttf': 'application/font-ttf',
+        '.eot': 'application/vnd.ms-fontobject',
+        '.otf': 'application/font-otf',
+        '.svg': 'application/image/svg+xml'
+    };
+
+    contentType = mimeTypes[extname] || 'application/octet-stream';
+
+    fs.readFile(filePath, function(error, content) {
+        if (error) {
+            if(error.code == 'ENOENT'){
+                fs.readFile('./404.html', function(error, content) {
+                    response.writeHead(200, { 'Content-Type': contentType });
+                    response.end(content, 'utf-8');
+                });
+            }
+            else {
+                response.writeHead(500);
+                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
+                response.end();
+            }
+        }
+        else {
+            response.writeHead(200, { 'Content-Type': contentType });
+            response.end(content, 'utf-8');
+        }
+    });
+
+}).listen(8125);
+console.log('Server running at http://127.0.0.1:8125/');
-- cgit v1.2.3-54-g00ecf