Node JS 시작하기

WBOY
풀어 주다: 2024-08-21 06:12:35
원래의
595명이 탐색했습니다.

Getting Started with Node JS

NodeJS란 무엇입니까?

  • 정의: NodeJS는 웹 브라우저 외부에서 JavaScript 코드를 실행할 수 있는 오픈 소스 크로스 플랫폼 JavaScript 런타임 환경입니다.
  • 목적: 주로 서버측 스크립팅에 사용됩니다. 여기서 JavaScript는 페이지가 사용자의 웹 브라우저로 전송되기 전에 동적 웹 콘텐츠를 생성하는 데 사용됩니다.
  • 주요 기능:
    • 이벤트 중심 아키텍처: NodeJS는 이벤트 중심의 비차단 I/O 모델을 사용하므로 효율적이고 가볍습니다.
    • 단일 스레드: 단일 스레드이지만 NodeJS는 비동기 특성과 이벤트 루프를 사용하여 동시 작업을 처리합니다.
    • V8 기반: NodeJS는 Google Chrome의 V8 JavaScript 엔진을 기반으로 구축되어 JavaScript 코드 실행 속도가 매우 빠릅니다.

NodeJS는 백그라운드에서 어떻게 작동하나요?

  • 이벤트 루프:

    • NodeJS는 단일 스레드 이벤트 루프에서 작동하므로 스레드를 차단하지 않고 여러 동시 요청을 처리할 수 있습니다.
    • 이벤트 루프의 단계:
    • 타이머: setTimeout() 및 setInterval()에 의해 예약된 콜백을 실행합니다.
    • 보류 중인 콜백: 다음 루프 반복으로 연기된 I/O 콜백을 실행합니다.
    • 유휴, 준비: NodeJS에서 내부적으로 사용됩니다.
    • Poll: 새로운 I/O 이벤트를 검색하고 I/O 관련 콜백을 실행합니다.
    • Check: setImmediate()에 의해 예약된 콜백을 실행합니다.
    • 닫기 콜백: 닫기 이벤트 콜백을 실행합니다.
  • 비차단 I/O: NodeJS는 I/O 작업을 비동기식으로 처리합니다. 즉, 작업이 완료될 때까지 기다리지 않고 다음 작업으로 넘어갑니다.

:

  const fs = require('fs');

  console.log("Start");

  // Reading a file asynchronously
  fs.readFile('example.txt', 'utf8', (err, data) => {
      if (err) throw err;
      console.log(data);
  });

  console.log("End");
로그인 후 복사

출력:

  Start
  End
  (contents of example.txt)
로그인 후 복사

설명:

  • NodeJS는 fs.readFile() 함수가 호출된 후에도 파일을 읽을 때까지 기다리지 않고 계속해서 코드를 실행합니다. 이는 비차단 I/O 모델을 보여줍니다.

NodeJS의 모듈이란 무엇입니까?

  • 정의: 모듈은 관련 기능을 기반으로 외부 애플리케이션과 통신하는 캡슐화된 코드 블록입니다.
  • 모듈 유형:
    • 핵심 모듈: NodeJS에 내장되어 있습니다(예: fs, http, path 등).
    • 로컬 모듈: 코드를 구성하고 구조화하기 위해 사용자가 생성합니다.
    • 타사 모듈: npm을 통해 설치됩니다(예: express, lodash).

JavaScript 및 NodeJS에서 모듈을 가져오고 내보내는 방법

JavaScript(ES6 모듈):

  • 내보내는 중:
  // Named export
  export const add = (a, b) => a + b;

  // Default export
  export default function subtract(a, b) {
      return a - b;
  }
로그인 후 복사
  • 가져오기:
  // Named import
  import { add } from './math.js';

  // Default import
  import subtract from './math.js';
로그인 후 복사

NodeJS(CommonJS 모듈)에서:

  • 내보내는 중:
  // Using module.exports
  module.exports.add = (a, b) => a + b;

  // Using exports shorthand
  exports.subtract = (a, b) => a - b;
로그인 후 복사
  • 가져오기:
  // Importing modules
  const math = require('./math.js');
  const add = math.add;
  const subtract = math.subtract;
로그인 후 복사

NodeJS의 파일 처리란 무엇입니까?

  • 정의: NodeJS의 파일 처리를 사용하면 파일 읽기, 쓰기, 업데이트, 삭제 등 컴퓨터의 파일 시스템 작업을 수행할 수 있습니다.

중요한 기능:

  • 가장 중요한 fs 모듈 기능 중 일부:
    • fs.readFile(): 파일의 내용을 비동기적으로 읽습니다.
    • fs.writeFile(): 데이터를 파일에 비동기식으로 쓰고 파일이 이미 있는 경우 파일을 바꿉니다.
    • fs.appendFile(): 파일에 데이터를 추가합니다. 해당 파일이 없으면 새로운 파일을 생성합니다.
    • fs.unlink(): 파일을 삭제합니다.
    • fs.rename(): 파일 이름을 바꿉니다.

:

  const fs = require('fs');

  // Writing to a file
  fs.writeFile('example.txt', 'Hello, NodeJS!', (err) => {
      if (err) throw err;
      console.log('File written successfully.');

      // Reading the file
      fs.readFile('example.txt', 'utf8', (err, data) => {
          if (err) throw err;
          console.log('File contents:', data);

          // Appending to the file
          fs.appendFile('example.txt', ' This is an appended text.', (err) => {
              if (err) throw err;
              console.log('File appended successfully.');

              // Renaming the file
              fs.rename('example.txt', 'newExample.txt', (err) => {
                  if (err) throw err;
                  console.log('File renamed successfully.');

                  // Deleting the file
                  fs.unlink('newExample.txt', (err) => {
                      if (err) throw err;
                      console.log('File deleted successfully.');
                  });
              });
          });
      });
  });
로그인 후 복사

출력:

  File written successfully.
  File contents: Hello, NodeJS!
  File appended successfully.
  File renamed successfully.
  File deleted successfully.
로그인 후 복사

NodeJS에서 서버를 구축하는 방법은 무엇입니까?

  • http 모듈 사용: http 모듈은 NodeJS의 핵심 모듈로, 특정 포트에서 요청을 수신하고 응답을 보내는 서버를 만들 수 있습니다.

:

  const http = require('http');

  // Creating a server
  const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello, World!\n');
  });

  // Listening on port 3000
  server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
  });
로그인 후 복사

출력:

  Server running at http://127.0.0.1:3000/
로그인 후 복사
  • Explanation: The server responds with "Hello, World!" every time it receives a request. The server listens on localhost (127.0.0.1) at port 3000.

What is an HTTP Module?

  • Definition: The http module in NodeJS provides functionalities to create HTTP servers and clients.

Important Functions?

  • Some of the most important functions of HTTP module are:
    • http.createServer(): Creates an HTTP server that listens to requests and sends responses.
    • req.method: Retrieves the request method (GET, POST, etc.).
    • req.url: Retrieves the URL of the request.
    • res.writeHead(): Sets the status code and headers for the response.
    • res.end(): Signals to the server that all of the response headers and body have been sent.

Example:

  const http = require('http');

  const server = http.createServer((req, res) => {
      if (req.url === '/') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the homepage!\n');
      } else if (req.url === '/about') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the about page!\n');
      } else {
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('404 Not Found\n');
      }
  });

  server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
  });
로그인 후 복사

Output:

  • If you navigate to http://127.0.0.1:3000/, the server will display "Welcome to the homepage!".
  • If you navigate to http://127.0.0.1:3000/about, the server will display "Welcome to the about page!".
  • If you navigate to any other URL, the server will display "404 Not Found".

위 내용은 Node JS 시작하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!