Problem Solving with Algorithms

반응형

 

If you have ever heard about Node.js then you might know that it is one the most prominent and powerful frameworks of JavaScript. Since its release, it has continued to keep its stranglehold on the IT market. Even with the introduction of new and vibrant JS Frameworks like Angular, React, Meteor etc., the popularity of Node.js never seems to cease. Wondering why? Well, with the help of this Node.js Tutorial, I will be giving you a complete insight into it. So, get ready to fall in love with Node.js.

In this Node.js Tutorial, I will be discussing the below topics:

Node.js에 대해 들어 본 적이 있다면 이것이 가장 눈에 띄고 강력한 JavaScript 프레임 워크 중 하나라는 것을 알고있을 것입니다. 출시 이후 IT 시장에서 계속해서 목을 졸라 매고 있습니다. Angular , React , Meteor 등과 같은 새롭고 생생한 JS 프레임 워크 가 도입 되었음에도 불구하고 Node.js의 인기는 멈추지 않는 것 같습니다. 이유가 궁금하세요? 이 Node.js 자습서의 도움으로 이에 대한 완전한 통찰력을 제공 할 것입니다. 따라서 Node.js와 사랑에 빠질 준비를하십시오.

이 Node.js 튜토리얼에서는 아래 주제에 대해 논의 할 것입니다.

 

 

 

 

 

 

What is Node.js?

Node.js is a powerful framework developed on Chrome’s V8 JavaScript engine that compiles the JavaScript directly into the native machine code. It is a lightweight framework used for creating server-side web applications and extends JavaScript API to offer usual server-side functionalities. It is generally used for large-scale application development, especially for video streaming sites, single page application, and other web applications. Node.js makes use of an event-driven, non-blocking I/O model which makes it a right pick for the data-intensive real-time applications.

Like any other programming languages, node.js makes use of packages and modules. These are the libraries that contain various functions and are imported from npm (node package manager) into our code and utilized in the programs. Some of the major features, that define Node.js are listed below:

 

Node.js 란 무엇입니까?

Node.js는 자바 스크립트를 네이티브 기계어 코드로 직접 컴파일하는 Chrome의 V8 자바 스크립트 엔진에서 개발 된 강력한 프레임 워크 입니다. 서버 측 웹 애플리케이션을 생성하는 데 사용되는 경량 프레임 워크이며 일반적인 서버 측 기능을 제공하도록 JavaScript API를 확장합니다. 일반적으로 대규모 애플리케이션 개발, 특히 비디오 스트리밍 사이트, 단일 페이지 애플리케이션 및 기타 웹 애플리케이션에 사용됩니다. Node.js 는  이벤트 중심의 비 차단 I / O 모델을 사용하므로 데이터 집약적 인 실시간 애플리케이션에 적합합니다.

다른 프로그래밍 언어와 마찬가지로 node.js는 패키지와 모듈을 사용합니다. 이들은 다양한 기능을 포함하고 있으며 npm (노드 패키지 관리자)에서 우리 코드로 가져 와서 프로그램에서 활용되는 라이브러리입니다. Node.js를 정의하는 몇 가지 주요 기능은 다음과 같습니다.

 

 

Features of Node.js

  1. Open Source
    Node.js is an open source framework MIT license that is supported by a huge community. Its community is pretty much active have contributed to add new capabilities to Node.js applications.
  2. Simple and Fast
    Since Node.js is built on Google Chrome’s V8 JavaScript Engine, its libraries are capable of fast code execution.
  3. Asynchronous
    All the libraries of Node.js are asynchronous which means the Node.js based servers never wait for an API to send back the response and move on to the next API.
  4. High Scalability
    Because of the event mechanism, Node.js is highly scalable and aids the server in a non-blocking response.
  5. Single-Threaded
    With the help of event looping, Node.js is able to follow the single-threaded model. This lets a single program to handle multiple requests.
  6. No Buffering
    One of the major functionalities of Node.js applications is that it never buffers any data.
  7. Cross-Platform
    Node.js can be easily built and deployed on various platforms like Windows, MAC, and Linux.

Let’s now advance further and see how to deploy the actual code on the browser. But before that, you need to download and install in your systems. You can refer my other article to know the complete Node.js installation process.

So now, let’s move further in this Node.js Tutorial, where I will talk about the most important component of Node.js i.e., npm.

 

Node.js의 기능

  1. 오픈 소스
    Node.js는 거대한 커뮤니티에서 지원하는 오픈 소스 프레임 워크 MIT 라이선스입니다. 커뮤니티는 매우 활발하게 Node.js 애플리케이션에 새로운 기능을 추가하는 데 기여했습니다.
  2. 간단하고 빠름
    Node.js는 Google 크롬의 V8 JavaScript 엔진을 기반으로하므로 라이브러리는 빠른 코드 실행이 가능합니다.
  3. 비동기식
    Node.js의 모든 라이브러리는 비동기식이므로 Node.js 기반 서버는 API가 응답을 다시 보내고 다음 API로 이동할 때까지 기다리지 않습니다.
  4. 높은 확장 성
    이벤트 메커니즘으로 인해 Node.js는 확장 성이 뛰어나며 비 차단 응답으로 서버를 지원합니다.
  5. 단일 스레드
    이벤트 루프의 도움으로 Node.js는 단일 스레드 모델을 따를 수 있습니다. 이를 통해 단일 프로그램이 여러 요청을 처리 할 수 ​​있습니다.
  6. 버퍼링 없음
    Node.js 애플리케이션의 주요 기능 중 하나는 데이터를 버퍼링하지 않는다는 것입니다.
  7. Cross-Platform
    Node.js는 Windows, MAC 및 Linux와 같은 다양한 플랫폼에서 쉽게 구축하고 배포 할 수 있습니다.

이제 더 나아가 브라우저에 실제 코드를 배포하는 방법을 살펴 보겠습니다. 그러나 그 전에 시스템에 다운로드하여 설치해야합니다. 전체 Node.js 설치 프로세스 를 알기 위해 다른 기사를 참조 할 수 있습니다 .

이제 Node.js 튜토리얼에서 더 나아가서 Node.js의 가장 중요한 구성 요소 인 npm에 대해 이야기하겠습니다.

 

 

 

NPM (Node Package Manager)

NPM stands for Node Package Manager which as the name suggests is a package manager for Node.js packages/modules. From Node version 0.6.0. onwards, npm has been added as default in the node installation. It saves you from the hassle of installing npm explicitly.

NPM basically helps in two ways:

  1. Provides and hosts Online repositories for node.js packages/modules which can be easily downloaded and used in our projects. You can find them here: npmjs.com
  2. Provides the Command line utility in order to install various Node.js packages, manage Node.js versions and dependencies of the packages.

But now, you must be wondering what exactly these modules are and how do they help us in building the Node.js applications. Well, in the next section of this Node.js tutorial, I will give you a complete insight into Node.js modules.

 

NPM (노드 패키지 관리자)

NPM은 이름에서 알 수 있듯이 Node.js 패키지 / 모듈의 패키지 관리자 인 Node Package Manager의 약자입니다. Node 버전 0.6.0부터. 이후에는 노드 설치에 npm이 기본값으로 추가되었습니다. npm을 명시 적으로 설치하는 번거 로움을 덜어줍니다.

NPM은 기본적으로 두 가지 방법으로 도움이됩니다.

  1. 프로젝트에서 쉽게 다운로드하고 사용할 수있는 node.js 패키지 / 모듈에 대한 온라인 저장소를 제공하고 호스팅합니다. 여기에서 찾을 수 있습니다 : npmjs.com
  2. 다양한 Node.js 패키지 설치, Node.js 버전 및 패키지 종속성 관리를위한 명령 줄 유틸리티를 제공합니다.

하지만 이제이 모듈이 정확히 무엇인지, 그리고 Node.js 애플리케이션을 빌드하는 데 어떻게 도움이되는지 궁금 할 것입니다. 이 Node.js 튜토리얼의 다음 섹션에서는 Node.js 모듈에 대한 완전한 통찰력을 제공 할 것입니다.

 

 

Node.js Modules

The modules in Node.js represents various functionalities that are bundled up into single or multiple JS files. These modules have a unique context, thus, they never interfere nor pollute the scope of other modules.

These modules enable the code reusability and enhance the ease of usage. Node.js basically provides three types of modules:

  1. Core Modules
  2. Local Modules
  3. Third-Party Modules

Node.js 모듈

Node.js의 모듈은 단일 또는 여러 JS 파일에 번들로 제공되는 다양한 기능을 나타냅니다. 이러한 모듈에는 고유 한 컨텍스트가 있으므로 다른 모듈의 범위를 방해하거나 오염시키지 않습니다.

이러한 모듈은 코드 재사용을 가능하게하고 사용 편의성을 향상시킵니다. Node.js는 기본적으로 세 가지 유형의 모듈을 제공합니다.

  1. 핵심 모듈
  2. 로컬 모듈
  3. 타사 모듈

 

 

 

 

 

Core Module

Since Node.js is a very lightweight framework, the core modules bundle the absolute minimum functionalities. These modules generally get loaded when the Node process starts its execution. All you need to do is, import these core modules in order to use them in your code.

Below I have listed down a few of the important Core modules.

Core Module  Description
http Contains classes, methods, and events required to create Node.js HTTP server
url Contains methods for URL resolution and parsing in Node
querystring Contains methods to deal with a query string of Node
path Contains methods to deal with file paths
fs Contains classes, methods, and events to work with file I/O
util Contains utility functions that can be useful for programmers

You can load your core module, using the below code:

1

var module = require('module_name');

Lets now see, what are ‘local modules’.

핵심 모듈

Node.js는 매우 가벼운 프레임 워크이므로 핵심 모듈은 절대 최소 기능을 번들로 제공합니다. 이러한 모듈은 일반적으로 노드 프로세스가 실행을 시작할 때로드됩니다. 코드에서 사용하기 위해 이러한 핵심 모듈을 가져 오기만하면됩니다.

아래에 몇 가지 중요한 핵심 모듈을 나열했습니다.

핵심 모듈  기술
http Node.js HTTP 서버를 만드는 데 필요한 클래스, 메서드 및 이벤트를 포함합니다.
URL Node에서 URL 확인 및 구문 분석을위한 메서드를 포함합니다.
쿼리 문자열 Node의 쿼리 문자열을 처리하는 메서드를 포함합니다.
통로 파일 경로를 처리하는 방법을 포함합니다.
fs 파일 I / O 작업을위한 클래스, 메서드 및 이벤트 포함
util 프로그래머에게 유용 할 수있는 유틸리티 함수 포함

아래 코드를 사용하여 핵심 모듈을로드 할 수 있습니다.

1

var module = require('module_name');

이제 '로컬 모듈'이 무엇인지 살펴 보겠습니다.

 

 

 

 

 

Local Modules

The local modules of Node.js are custom modules that are created locally by user/developer in the application. These modules can include various functionalities bundled into distinct files and folders which can be easily distributed in the Node.js community using NPM.

These modules are loaded in a similar way to core modules. Let show you, how to do it using a basic example.

Create your custom/local module.js file

1

2

3

4

5

6

7

8

9

10

var detail = {

  name: function (name) {

    console.log('Name: ' + name);

  },

  domain:function (domain) {

    console.log('Domain: ' + domain);

  }

};

 

module.exports = detail;

Include your module file in your main application file.

1

2

3

var myLogModule = require('./Local_module.js');

myLogModule.name('Edureka');

myLogModule.domain('Education');

Now you can execute these files using below command:

1

node application.js

Let me now show you what are external modules.

 

로컬 모듈

Node.js의 로컬 모듈은 애플리케이션에서 사용자 / 개발자가 로컬로 생성 한 사용자 지정 모듈입니다. 이러한 모듈에는 NPM을 사용하여 Node.js 커뮤니티에서 쉽게 배포 할 수있는 개별 파일 및 폴더에 번들로 제공되는 다양한 기능이 포함될 수 있습니다.

이러한 모듈은 핵심 모듈과 유사한 방식으로로드됩니다. 기본 예를 사용하여 수행하는 방법을 보여 드리겠습니다.

사용자 정의 / 로컬 module.js 파일 만들기

1

2

4

5

6

7

8

9

10

var detail = {

  name: function (name) {

    console.log('Name: ' + name);

  },

  domain:function (domain) {

    console.log('Domain: ' + domain);

  }

};

 

module.exports = detail;

기본 애플리케이션 파일에 모듈 파일을 포함하십시오.

1

2

var myLogModule = require('./Local_module.js');

myLogModule.name('Edureka');

myLogModule.domain('Education');

이제 아래 명령을 사용하여 이러한 파일을 실행할 수 있습니다.

1

node application.js

이제 외부 모듈이 무엇인지 보여 드리겠습니다.

 

 

 

 

 

External Modules

You can use the external or 3rd party modules only by downloading them via NPM. These modules are generally developed by other developers and are free to use. Few of the best external modules are express, react, gulp, mongoose, mocha etc.

Globally Loading the 3rd party modules:

 

외부 모듈

당신은 외부 또는 3 사용할 수 있습니다 번째의 유일한 NPM을 통해이를 다운로드하여 자 모듈을. 이러한 모듈은 일반적으로 다른 개발자가 개발하며 무료로 사용할 수 있습니다. 최고의 외부 모듈은 express, react, gulp, mongoose, mocha 등입니다.

타사 모듈 전역로드 :

Node.js Certification Training

  • Instructor-led Sessions
  • Assignments
  • Lifetime Access
  • 24 x 7 Expert Support

Explore Curriculum

1

npm install --g <module_name>

Include your module file in your main application file:

1

npm install --save <module_name>

1

npm install --g <module_name>

기본 애플리케이션 파일에 모듈 파일을 포함합니다.

1

npm install --save <module_name>

 

 

JSON File

The package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project. Thus, understanding and working with this file becomes very important for a successful Node project development.

The package.json file generally consists of the metadata of the application, which is further categorized into below two categories:

  1. Identifying metadata properties: This consists of properties like the project name, current module version, license, author of the project, project description etc.
  1. Writing directly to file: You can directly write the necessary information into the package.json file and include it, in your project.

By now you have already familiarized with the various components of Node JS application. In the next section of this Node.js Tutorial, I will be sharing some Node Js basics so that we can start off with the hands on.

 

JSON 파일

 Node.js 의  package.json 파일 은 전체 애플리케이션의 핵심입니다. 기본적으로 프로젝트의 메타 데이터를 포함하는 매니페스트 파일입니다. 따라서이 파일을 이해하고 작업하는 것은 성공적인 Node 프로젝트 개발을 위해 매우 중요합니다.

package.json 파일은 일반적으로 응용 프로그램의 메타 데이터로 구성되며 다음 두 범주로 더 분류됩니다.

  1. 메타 데이터 속성 식별 : 프로젝트 이름, 현재 모듈 버전, 라이선스, 프로젝트 작성자, 프로젝트 설명 등과 같은 속성으로 구성됩니다.
  1. 파일에 직접 쓰기  필요한 정보를 package.json 파일에 직접 쓰고 프로젝트에 포함 할 수 있습니다.

이제 이미 Node JS 애플리케이션의 다양한 구성 요소에 익숙해졌습니다. 이 Node.js 튜토리얼의 다음 섹션에서는 실습을 시작할 수 있도록 몇 가지 Node Js 기본 사항을 공유 할 것입니다.

 

 

Node.js Basics

Since Node.js is a JavaScript framework, it uses the JavaScript syntax. If you want to learn JavaScript in detail, you can refer to this JavaScript Tutorial. For now, I will be brushing you up with some Node.js basics like:

Data Types

Like any other programming language, Node.js has various datatypes, which are further categorized into Primitive and Non-Primitive datatypes.

Primitive Data Types are:

  1. String
  2. Number
  3. Boolean
  4. Null
  5. Undefined

Non-Primitive Data Types are:

  1. Object
  2. Date
  3. Array

Node.js 기본 사항

Node.js는 JavaScript 프레임 워크이므로 JavaScript 구문을 사용합니다. JavaScript를 자세히 배우고 싶다면이 JavaScript Tutorial을 참조하십시오 . 지금은 다음과 같은 Node.js 기본 사항을 살펴 보겠습니다.

데이터 유형

다른 프로그래밍 언어와 마찬가지로 Node.js에는 다양한 데이터 유형이 있으며, 이는 기본 및 비 기본 데이터 유형으로 더 분류됩니다.

기본 데이터 유형은 다음과 같습니다.

  1. 번호
  2. 부울
  3. 없는
  4. 찾으시는 주소가 없습니다

비 원시적 데이터 유형은 다음과 같습니다.

  1. 목적
  2. 데이트
  3. 정렬

 

 

 

 

Variables

Variable are entities that hold values which may vary during the course of a program. To create a variable in Node.js, you need to make use of a reserved keyword var. You do not have to assign a data type, as the compiler will automatically pick it.

Syntax:

1

var varName = value;

Operators

Node.js supports the below operators:

Operator Type Operators
Arithmetic +, -, /, *,  %, ++, —
Assignment =, +=, -=, *=, /=, %=
Conditional =?
Comparison ==, ===, !=, !==, >, >=, <, <=,
Logical &&, ||, !
Bitwise &, |, ^, ~, <<, >>, >>>

변수

변수는 프로그램 과정에서 달라질 수있는 값을 보유하는 개체입니다. Node.js에서 변수를 만들려면 예약 된 키워드 var를 사용해야합니다. 컴파일러가 자동으로 데이터 유형을 선택하므로 데이터 유형을 지정할 필요가 없습니다.

통사론:

1

var varName = value;

연산자

Node.js는 다음 연산자를 지원합니다.

연산자 유형 연산자
산수 +,-, /, *, %, ++, —
할당 =, + =,-=, * =, / =, % =
가정 어구 =?
비교 ==, ===,! =,! ==,>,> =, <, <=,
논리적 &&, ||,!
비트 &, |, ^, ~, <<, >>, >>>

 

 

 

Functions

Functions in Node.js is a block of code that has a name and is written to achieve a particular task. You need to use the keyword function to create it. A function is generally a two-step process. First is defining the function and the second is invoking it. Below is the syntax of creating and invoking a function:

Example:

1

2

3

4

5

6

7

//Defining a function

function display_Name(firstName, lastName) {

  alert("Hello " + firstName + " " + lastName);

}

 

//Invoking the function

display_Name("Park", "Jimin");

Objects

An object is a non-primitive data type that can hold multiple values in terms of properties and methods. Node.js objects are standalone entities as there is no concept of class. You can create an object in two ways:

  1. Using Object literal
  2. Using Object constructor

Example:

1

2

3

4

5

6

7

8

9

10

11

12

// object with properties and method

var employee = {

  //properties

  firstName: "Minho",

  lastName: "Choi",

  age: 35,

  salary:50000,

  //method

  getFullName: function () {

    return this.firstName + ' ' + this.lastName

  }

};

기능

Node.js의 함수는 이름이 있고 특정 작업을 수행하기 위해 작성된 코드 블록입니다. 그것을 만들려면 키워드 함수를 사용해야합니다. 함수는 일반적으로 2 단계 프로세스입니다. 첫 번째는 함수를 정의하고 두 번째는 함수를 호출하는 것입니다. 다음은 함수를 만들고 호출하는 구문입니다.

예:

1

2

4

5

6

7

//Defining a function

function display_Name(firstName, lastName) {

  alert("Hello " + firstName + " " + lastName);

}

 

//Invoking the function

display_Name("Park", "Jimin");

사물

객체는 속성 및 메서드 측면에서 여러 값을 보유 할 수있는 기본이 아닌 데이터 유형입니다. Node.js 객체는 클래스 개념이 없으므로 독립형 엔티티입니다. 두 가지 방법으로 개체를 만들 수 있습니다.

  1. 개체 리터럴 사용
  2. 개체 생성자 사용

예:

1

2

4

5

6

7

8

9

10

11

12

// object with properties and method

var employee = {

  //properties

  firstName: "Minho",

  lastName: "Choi",

  age: 35,

  salary:50000,

  //method

  getFullName: function () {

    return this.firstName + ' ' + this.lastName

  }

};

 

 

 

File System

To access the physical file system, Node.js makes use of the fs module which basically takes care of all asynchronous and synchronous file I/O operations. This module is imported using the below command:

1

var fs = require('fs');

Some of the general use for the File System modules are:

  • Read files
    1. fs.readFile()

1

2

3

4

5

6

7

8

9

var http = require('http');

var fs = require('fs');

http.createServer(function (req, res) {

  fs.readFile('script.txt', function(err, data) {

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write(data);

    res.end();

  });

}).listen(8080);

  • Create files
    1. appendFile()
    2. open()
    3. writeFile()
  • Update files
    1. fs.appendFile()
    2. fs.writeFile()
  • Delete files
    1. fs.unlink()
  • Rename files
    1. fs.rename()

So, with these commands, you can pretty much perform all the required operations on your files. Let’s now move further with this Node.js Tutorial and see what are Events and how they are handled in Node.js.

파일 시스템

물리적 파일 시스템에 액세스하기 위해 Node.js는  기본적으로 모든 비동기 및 동기 파일 I / O 작업을 처리 하는 fs 모듈을 사용  합니다. 이 모듈은 아래 명령을 사용하여 가져옵니다.

1

var fs = require('fs');

파일 시스템 모듈의 일반적인 용도는 다음과 같습니다.

  • 파일 읽기
    1. fs.readFile ()

1

2

4

5

6

7

8

9

var http = require('http');

var fs = require('fs');

http.createServer(function (req, res) {

  fs.readFile('script.txt', function(err, data) {

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write(data);

    res.end();

  });

}).listen(8080);

  • 파일 생성
    1. appendFile ()
    2. 열다()
    3. writeFile ()
  • 파일 업데이트
    1. fs.appendFile ()
    2. fs.writeFile ()
  • 파일을 지우시오
    1. fs.unlink ()
  • 파일 이름 바꾸기
    1. fs.rename ()

따라서 이러한 명령을 사용하면 파일에 필요한 모든 작업을 거의 수행 할 수 있습니다. 이제이 Node.js 튜토리얼을 통해 더 나아가 이벤트가 무엇이며 Node.js에서 어떻게 처리되는지 살펴 보겠습니다.

 

 

 

 

Events

As I have already mentioned, Node.js applications are single threaded and event-driven. Node.js supports concurrency as it is event-driven, and thus makes use of concepts like events and callbacks. The async function calls help Node.js in maintaining concurrency throughout the application.

Basically, in a Node.js application, there is a main loop which waits and listens for events, and once any event is completed, it immediately initiates a callback function.

Below diagram represents how the events are driven in Node.js.

One thing that you must note here is that, even though events look similar to callback functions but the difference lies in their functionalities. When an asynchronous function returns its results callbacks are invoked on the other hand event handling completely works on the observer pattern. And in Node.js, methods which listen to the events are called the observers. The moment, an event is triggered, its listener function automatically starts executing. Event modules and EventEmitter class provide multiple in-built events which are used to bind events with event listeners. Below I have written down the syntax for that.

 

이벤트

이미 언급했듯이 Node.js 애플리케이션은 단일 스레드 및 이벤트 기반입니다. Node.js는 이벤트 기반이므로 동시성을 지원하므로 이벤트 및 콜백과 같은 개념을 사용합니다. 비동기 함수 호출은 Node.js가 애플리케이션 전체에서 동시성을 유지하도록 도와줍니다.

기본적으로 Node.js 애플리케이션에는 이벤트를 대기하고 수신하는 메인 루프가 있으며 이벤트가 완료되면 즉시 콜백 함수를 시작합니다.

아래 다이어그램은 Node.js에서 이벤트가 구동되는 방식을 나타냅니다.

여기서 주목해야 할 한 가지는 이벤트가 콜백 함수와 비슷해 보이지만 차이점은 기능에 있다는 것입니다. 비동기 함수가 결과를 반환하면 콜백이 호출되는 반면 이벤트 처리는 관찰자 패턴에서 완전히 작동합니다. 그리고 Node.js에서는 이벤트를 수신하는 메서드를 관찰자라고합니다. 이벤트가 트리거되는 순간 리스너 기능이 자동으로 실행되기 시작합니다. 이벤트 모듈 및 EventEmitter 클래스는 이벤트 리스너와 이벤트를 바인딩하는 데 사용되는 여러 내장 이벤트를 제공합니다. 아래에 이에 대한 구문을 작성했습니다.

 

Binding Event to an Event Listener

1

2

3

4

// Import events module

var my_Events = require('events');

// Create an eventEmitter object

var my_EveEmitter = new my_Events.EventEmitter();

Binding Event Handler to an Event

1

2

// Binding event and event handler

my_EveEmitter.on('eventName', eventHandler);

Firing an Event 

1

2

// Fire an event

my_EveEmitter.emit('eventName');

Now let’s try to implement the things that I have discussed in this Node.js Event section. The below code shows a simple representation of Event execution in Node.js.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

var emitter = require('events').EventEmitter;

function iterateProcessor(num) {

  var emt = new emitter();

  setTimeout(function () {

        for (var i = 1; i <= num; i++) {

          emt.emit('BeforeProcess', i);

          console.log('Processing Iteration:' + i);

          emt.emit('AfterProcess', i);

        }

      }

      , 5000)

  return emt;

}

var it = iterateProcessor(5);

 

it.on('BeforeProcess', function (info) {

  console.log('Starting the process for ' + info);

});

 

it.on('AfterProcess', function (info) {

  console.log('Finishing processing for ' + info);

In the next section of this Node.js Tutorial, I will give you insights on one of the most important module of Node.js called the HTTP Module.

이벤트 리스너에 이벤트 바인딩

1

2

4

// Import events module

var my_Events = require('events');

// Create an eventEmitter object

var my_EveEmitter = new my_Events.EventEmitter();

이벤트에 이벤트 처리기 바인딩

1

2

// Binding event and event handler

my_EveEmitter.on('eventName', eventHandler);

이벤트 실행 

1

2

// Fire an event

my_EveEmitter.emit('eventName');

이제이 Node.js 이벤트 섹션에서 논의한 것들을 구현해 보겠습니다. 아래 코드는 Node.js에서 이벤트 실행의 간단한 표현을 보여줍니다.

1

2

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

var emitter = require('events').EventEmitter;

function iterateProcessor(num) {

  var emt = new emitter();

  setTimeout(function () {

        for (var i = 1; i <= num; i++) {

          emt.emit('BeforeProcess', i);

          console.log('Processing Iteration:' + i);

          emt.emit('AfterProcess', i);

        }

      }

      , 5000)

  return emt;

}

var it = iterateProcessor(5);

 

it.on('BeforeProcess', function (info) {

  console.log('Starting the process for ' + info);

});

 

it.on('AfterProcess', function (info) {

  console.log('Finishing processing for ' + info);

이 Node.js 자습서의 다음 섹션에서는 Node.js의 가장 중요한 모듈 중 하나 인 HTTP 모듈에 대한 통찰력을 제공합니다.

 

 

 

 

HTTP Module

Generally, Node.js is used for developing server-based applications. But using the module, you can easily create web servers that can respond to the client requests. Thus it is also referred to Web Module and provides modules like HTTP and request that facilitate Node.js in processing the server requests.

You can easily include this module in your Node.js application just by writing the below code:

1

var http = require('http');

Below I have written a code, that shows how a Web Server is developed in Node.js.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//calling http library

var http = require('http');

var url = require('url');

 

//creating server

var server = http.createServer(function (req, res) {

  //setting content header

  res.writeHead(200, ('Content-Type', 'text/html'));

  var q = url.parse(req.url, true).query;

  var txt = q.year + " " + q.month;

  //send string to response

  res.end(txt);

});

 

//assigning 8082 as server listening port

server.listen(8082);

In the next section of this Node.js Tutorial, I will be talking about Express.js which is heavily used for server-side web application development.

HTTP 모듈

일반적으로 Node.js는 서버 기반 애플리케이션 개발에 사용됩니다. 그러나 모듈을 사용하면 클라이언트 요청에 응답 할 수있는 웹 서버를 쉽게 만들 수 있습니다. 따라서 Web Module이라고도하며 서버 요청을 처리 할 때 Node.js를 용이하게하는 HTTP 및 요청과 같은 모듈을 제공합니다.

아래 코드를 작성하여 Node.js 애플리케이션에이 모듈을 쉽게 포함 할 수 있습니다.

1

var http = require('http');

아래에 Node.js에서 웹 서버가 어떻게 개발되는지 보여주는 코드를 작성했습니다.

1

2

4

5

6

7

8

9

10

11

12

13

14

15

16

//calling http library

var http = require('http');

var url = require('url');

 

//creating server

var server = http.createServer(function (req, res) {

  //setting content header

  res.writeHead(200, ('Content-Type', 'text/html'));

  var q = url.parse(req.url, true).query;

  var txt = q.year + " " + q.month;

  //send string to response

  res.end(txt);

});

 

//assigning 8082 as server listening port

server.listen(8082);

이 Node.js 튜토리얼의 다음 섹션에서는 서버 측 웹 애플리케이션 개발에 많이 사용되는 Express.js에 대해 이야기 할 것입니다.

 

 

 

Express.js

Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications.  It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development.

Express.js is developed on the middleware module of Node.js called connect. The connect module further makes use of http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.

 Not, only this, few of the major advantages of Express.js are:

  • Makes web application development faster
  • Helps in building mobile and web application of single-page, multi-page, and hybrid types
  • Express provides two templating engines namely, Jade and EJS
  • Express follows the Model-View-Controller (MVC) architecture
  • Makes integration with databases such as MongoDB, Redis, MySQL
  • Defines an error handling middleware
  • Simplifies configuration and customization easy for the application.

With all these features, Express takes responsibility of backend part in the MEAN stack. Mean Stack is the open-source JavaScript software stack that is used for building dynamic websites and web applications. Here, MEANstands for MongoDB, Express.js, AngularJS, and Node.js.

Lets now see a simple example to understand, how Express.js works with Node.js to ease our work. But before you start working with Express.js, you need to install it in your system.

To install Express.js globally you can use the below command:

1

npm install -g express

Or, if you want to install it locally into your project folder, you need to execute the below command:

1

npm install express --save

Since we are done with all the preparations, let’s now jump directly into practical implementation. Here, I will be showing a simple User Authentication Application using Node.js and Express.js.

Express.js

Express.js는 Node.js를 기반으로 구축 된 프레임 워크로, 서버 측 애플리케이션에서 서버와 경로 간의 데이터 흐름 관리를 용이하게합니다. 웹 및 모바일 애플리케이션 개발에 필요한 다양한 기능을 제공하는 가볍고 유연한 프레임 워크입니다.

Express.js는 connect 라는 Node.js의 미들웨어 모듈에서 개발되었습니다  . connect 모듈은 http  모듈을 사용  하여 Node.js와 통신합니다. 따라서 연결 기반 미들웨어 모듈로 작업하는 경우 Express.js와 쉽게 통합 할 수 있습니다.

 뿐만 아니라 Express.js의 주요 장점은 다음과 같습니다.

  • 웹 애플리케이션 개발 속도를 높입니다.
  • 단일 페이지, 다중 페이지 및 하이브리드 유형의 모바일 및 웹 애플리케이션 구축에 도움이됩니다.
  • Express는 Jade와 EJS라는 두 가지 템플릿 엔진을 제공합니다.
  • Express는 MVC (Model-View-Controller) 아키텍처를 따릅니다.
  • MongoDB, Redis, MySQL과 같은 데이터베이스와 통합
  • 오류 처리 미들웨어를 정의합니다.
  • 응용 프로그램에 대한 구성 및 사용자 정의를 쉽게 단순화합니다.

이러한 모든 기능을 통해 Express는 MEAN 스택의 백엔드 부분을 담당합니다. Mean Stack은 동적 웹 사이트 및 웹 애플리케이션을 구축하는 데 사용되는 오픈 소스 JavaScript 소프트웨어 스택입니다. 여기서  MEAN 은  M ongoDB,  E xpress.js,  A ngularJS 및  N ode.js를 나타냅니다.

이제 Express.js가 Node.js와 함께 작동하여 작업을 용이하게하는 방법을 이해하는 간단한 예제를 살펴 보겠습니다. 그러나 Express.js로 작업을 시작하기 전에 시스템에 설치해야합니다.

Express.js를 전역으로 설치하려면 아래 명령을 사용할 수 있습니다.

1

npm install -g express

또는 프로젝트 폴더에 로컬로 설치하려면 아래 명령을 실행해야합니다.

1

npm install express --save

모든 준비를 마쳤으므로 이제 실제 구현으로 바로 이동하겠습니다. 여기에서는 Node.js와 Express.js를 사용한 간단한 사용자 인증 애플리케이션을 보여 드리겠습니다.

 

 

 

 

Node.js Tutorial Step By Step Application Development with Express.js

For this, we will be needing below files:

  • package.json
  • script.js
  • views
    • index.jade
    • login.jade
    • secure.jade
    • unauthorized.jade
    • welcome.jade
  • lib
    • routes.js

 

Express.js를 사용한 Node.js 자습서 단계별 애플리케이션 개발

이를 위해 아래 파일이 필요합니다.

  • package.json
  • script.js
  • 견해
    • index.jade
    • login.jade
    • secure.jade
    • 무단 .jade
    • welcome.jade
  • lib
    • route.js

자, package.json으로 시작하겠습니다 .

 

So, let’s start with package.json.

 

{
  "author": "Edureka",
  "name": "Express_Demo",
  "description": "Express with Node.js",
  "version": "0.0.0",
  "scripts": {
    "start": "node script.js"
  },
  "engines": {
    "node": "~0.4.12"
  },
  "dependencies": {
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "express": "^3.21.2",
    "jade": "^0.20.3",
    "req-flash": "0.0.3"
  },
  "devDependencies": {}
}

 

 

{ "author": "Edureka", "name": "Express_Demo", "description": "Express with Node.js", "version": "0.0.0", "scripts": { "start": "node script.js" }, "engines": { "node": "~0.4.12" }, "dependencies": { "connect-flash": "^0.1.1", "cookie-parser": "^1.4.3", "express": "^3.21.2", "jade": "^0.20.3", "req-flash": "0.0.3" }, "devDependencies": {} }

Next, you need to create the script.js.

 

var express = require('express');
var http = require('http');
var port = 8999;
var app = express();
const flash = require('connect-flash');
var cookieParser = require('cookie-parser')
var server = http.createServer(app);

function checkAuth (req, res, next) {
   console.log('checkAuth ' + req.url);

   // don't serve /secure to those not logged in
   if (req.url === '/secure' && (!req.session || !req.session.authenticated)) {
      res.render('unauthorised', { status: 403 });
      return;
   }

   next();
}
   app.use(flash());
   app.use(cookieParser());
   app.use(express.session({ secret: 'example' }));
   app.use(express.bodyParser());
   app.use(checkAuth);
   app.use(app.router);
   app.set('view engine', 'jade');
   app.set('view options', { layout: false });

require('./lib/routes.js')(app);

app.listen(port);
console.log('Node listening on port %s', port);

 

 

var express = require('express'); var http = require('http'); var port = 8999; var app = express(); const flash = require('connect-flash'); var cookieParser = require('cookie-parser') var server = http.createServer(app); function checkAuth (req, res, next) { console.log('checkAuth ' + req.url); // don't serve /secure to those not logged in if (req.url === '/secure' && (!req.session || !req.session.authenticated)) { res.render('unauthorised', { status: 403 }); return; } next(); } app.use(flash()); app.use(cookieParser()); app.use(express.session({ secret: 'example' })); app.use(express.bodyParser()); app.use(checkAuth); app.use(app.router); app.set('view engine', 'jade'); app.set('view options', { layout: false }); require('./lib/routes.js')(app); app.listen(port); console.log('Node listening on port %s', port);

Now, create a folder named view, under which you will be adding the jade files that will be responsible for various page views. The first view file you need to create is index.jade.

 

!!! 5
html(lang='en')
   head
      title User Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">

   body
      h1
         center Authentication Demo using Express
         h3 Navigate to
         h4
         ul
            li: a(href="/secure") Secure content
            li: a(href="/welcome") Welcome page
            li: a(href="/logout") Logout

 

 

 

!!! 5 html(lang='en') head title User Authentication Example body h1 center Authentication Demo using Express h3 Navigate to h4 ul li: a(href="/secure") Secure content li: a(href="/welcome") Welcome page li: a(href="/logout") Logout

Now, create the login.jade file.

 

!!! 5
html(lang='en')
   head
      title Express authentication example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Sign-in to this Express authentication example
      center
         p Use <i>user</i> for the username and <i>pass</i> for the password.

         form(method='post')
            p
            label(for='username') Email Address
            input(type='text', name='username', class='form-control', id='exampleInputPassword1' , placeholder='Email', style='width:400px;')
            p
            center
            label(for='password') Password
            input(type='password', name='password', class='form-control' , id='exampleInputPassword1', placeholder='Password', style='width:400px;')

            p
            center <button type="submit" class="btn btn-info">Submit</button>
      - each message in flash
         h4(style="color: red;") #{message}

 

 

!!! 5 html(lang='en') head title Express authentication example body h1 center Sign-in to this Express authentication example center p Use user for the username and pass for the password. form(method='post') p label(for='username') Email Address input(type='text', name='username', class='form-control', id='exampleInputPassword1' , placeholder='Email', style='width:400px;') p center label(for='password') Password input(type='password', name='password', class='form-control' , id='exampleInputPassword1', placeholder='Password', style='width:400px;') p center - each message in flash h4(style="color: red;") #{message}

Next step is to create the welcome.jade.

 

!!! 5
html(lang='en')
   head
      title User Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Welcome To The Edureka Tutorial!

 

!!! 5 html(lang='en') head title User Authentication Example body h1 center Welcome To The Edureka Tutorial!

Next, create the secure.jade file.

 

!!! 5
html(lang='en')
   head
      title Express Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Hi, secure user.
      p Navigate to
         ul
            li: a(href="/secure") Secure content
            li: a(href="/welcome") Welcome page
            li: a(href="/logout") Logout

 

 

!!! 5 html(lang='en') head title Express Authentication Example body h1 center Hi, secure user. p Navigate to ul li: a(href="/secure") Secure content li: a(href="/welcome") Welcome page li: a(href="/logout") Logout

Now, create the unauthorized.jade file.

 

!!! 5
html(lang='en')
   head
      title User Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Unauthorized
      p You're unauthorized to view this page.
      p Please <a href="/login">login</a> to continue

 

!!! 5 html(lang='en') head title User Authentication Example body h1 center Unauthorized p You're unauthorized to view this page. p Please login to continue

Now, you need to create a folder and name it lib. Now, create a route.js file which will map all the pages.

 

 

 

var util = require('util');
module.exports = function (app) {
   app.get('/', function (req, res, next) {
      res.render('index');
   }); 

   app.get('/welcome', function (req, res, next) {
      res.render('welcome');
   });

   app.get('/secure', function (req, res, next) {
      res.render('secure');
   });

   app.get('/login', function (req, res, next) {
      res.render('login', {flash: req.flash() } );
   });

   app.post('/login', function (req, res, next) {

      // you might like to do a database look-up or something more scalable here
      if (req.body.username && req.body.username === 'user' && req.body.password && req.body.password === 'pass') {
         req.session.authenticated = true;
         res.redirect('/secure');
      } else {
         req.flash('error', 'Username and password are incorrect');
         res.redirect('/login');
      }
   });

   app.get('/logout', function (req, res, next) {
      delete req.session.authenticated;
      res.redirect('/');
   });

};

 

 

 

Now if you want to execute this code on your own then you can download it from here: Node.js Tutorial PDF.

With this, we come to an end of this Node.js Tutorial. I hope I was able to explain the concepts of Node.js from the ground up. 

If you found this “Node.js Tutorial” relevant, check out the Node.js Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

Got a question for us? Please mention it in the comments section of this Node.js Tutorial and we will get back to you.

 

 

 

이제이 코드를 직접 실행하려면 여기에서 다운로드 할 수 있습니다. Node.js Tutorial PDF .

이것으로이 Node.js 튜토리얼을 마칩니다. Node.js의 개념을 처음부터 설명 할 수 있었으면합니다. 

이 "Node.js 자습서 "와 관련  이있는 경우 전 세계에 걸쳐 250,000 명 이상의 만족 한 학습자 네트워크를 보유한 신뢰할 수있는 온라인 학습 회사 인 Edureka  Node.js 인증 교육  확인하십시오   

질문이 있으십니까? 이 Node.js 튜토리얼의 댓글 섹션에 언급 해 주시면 다시 연락 드리겠습니다.

 

 

 

www.edureka.co/blog/nodejs-tutorial/

반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band