NodeJS를 시작하는 방법 – 초보자를 위한 핸드북

PHP中文网
풀어 주다: 2024-10-09 10:44:50
원래의
725명이 탐색했습니다.

Node란?

Node는 "웹 브라우저 외부"에서 JavaScript 코드를 실행할 수 있는 환경입니다. 노드는 다음과 같습니다. "안녕하세요. JS 코드를 저에게 주시면 제가 실행해 볼까요?" Google의 V8 엔진을 사용하여 JavaScript 코드를 기계 코드로 변환합니다.

Node는 웹 브라우저 외부에서 JavaScript 코드를 실행하므로 브라우저에서만 사용할 수 있는 특정 기능에 액세스할 수 없다는 의미입니다. DOM이나 창 개체 또는 심지어 localStorage와 같은 것입니다.

즉, 코드의 어떤 지점에서든 document.querySelector() 또는 Alert()를 입력하면 오류가 발생하므로(이것은 아래 이미지에 표시된 내용입니다).

기억하세요: Node는 서버 측 프로그래밍을 위한 반면 해당 브라우저 기능은 클라이언트 측 프로그래밍을 위한 것입니다.

Node does not know about Browser API's

프론트엔드 사람들은 슬퍼하지 마세요. 더 많은 일이 있습니다! Node는 파일 처리, 서버 생성 등과 같은 다양한 작업을 수행할 수 있는 많은 API와 모듈을 제공합니다. NodeJS를 시작하기 전에 먼저 우리 컴퓨터에 설치해 봅시다.

NodeJS 설치 방법

NodeJS 설치는 간단합니다. 컴퓨터에 Node가 이미 설치되어 있는 경우 이 섹션을 건너뛸 수 있습니다. 그렇지 않다면 따라 하세요.

컴퓨터에 NodeJS를 다운로드하는 단계는 다음과 같습니다.

  1. https://nodejs.org/로 이동
  2. 다운로드 운영 체제에 맞는 NodeJS LTS 버전
  3. 설치 프로그램을 실행하고 설치 마법사를 따르세요. 모든 질문에 예라고 대답하면 됩니다.
  4. 설치가 완료되면 새 터미널이나 명령 프롬프트 창을 열고 다음 명령을 실행하여 NodeJS가 올바르게 설치되었는지 확인하세요. node -v. 터미널에 NodeJS 버전이 인쇄되어 있으면 축하합니다! 이제 컴퓨터에 NodeJS가 성공적으로 설치되었습니다.

참고: 설치 과정에서 문제가 발생하면 공식 NodeJS 설명서를 참조하여 자세한 지침과 문제 해결 팁을 확인할 수 있습니다.

전역 변수

NodeJS에 존재하는 전역 변수라고 불리는 일부 변수에 대해 알아보는 것으로 이 글을 시작하겠습니다. 이는 기본적으로 일부 데이터를 저장하고 코드의 어느 곳에서나 액세스할 수 있는 변수입니다. 코드가 얼마나 깊이 중첩되어 있는지는 중요하지 않습니다.

일반적으로 사용되는 전역 변수에 대해 알아야 합니다.

  • __dirname: 현재 작업 디렉터리의 경로를 저장하는 변수입니다.
  • __filename: 현재 작업 중인 파일의 경로를 저장하는 변수입니다.

이를 사용하여 살펴보겠습니다. 어떤 가치가 포함되어 있는지. 이를 위해 데스크톱에 NodeJSTut이라는 새 폴더를 만들고 즐겨 사용하는 텍스트 편집기로 엽니다(전체 튜토리얼에서는 VS Code를 사용합니다). app.js라는 새 파일을 만들고 새로운 통합 VS Code 터미널을 엽니다.

Fügen Sie den folgenden Code in die Datei „app.js“ ein und speichern Sie ihn:

// __dirname Global Variableconsole.log(__dirname);// __filename Global Variableconsole.log(__filename);
로그인 후 복사

Um diesen Code mit Node auszuführen, geben Sie den folgenden Befehl in das Terminal ein und drücken Sie die Eingabetaste: node app.js. Sie sehen den absoluten Pfad zum aktuellen Arbeitsverzeichnis und der Pfad zur aktuellen Datei wird im Terminal ausgedruckt. So sieht die Ausgabe in meinem Fall aus:

C:\Desktop\NodeJSTut
C:\Desktop\NodeJSTut\app.js
로그인 후 복사

Sie können fortfahren und Ihre eigenen globalen Variablen erstellen, auf die Sie von überall in Ihrem Code aus zugreifen können. Sie können dies wie folgt tun:

// Define a global variable in NodeJSglobal.myVariable = 'Hello World';// Access the global variableconsole.log(myVariable); // Output: Hello World
로그인 후 복사

Module in NodeJS

In Node.js ist ein Modul im Wesentlichen ein wiederverwendbarer Codeblock, der zum Ausführen eines bestimmten Satzes von verwendet werden kann Aufgaben erledigen oder eine bestimmte Funktionalität bereitstellen. Ein Modul kann Variablen, Funktionen, Klassen, Objekte oder jeden anderen Code enthalten, der zum Ausführen einer bestimmten Aufgabe oder einer Reihe von Aufgaben verwendet werden kann.

Der Hauptzweck der Verwendung von Modulen in Node.js besteht darin, die Organisation zu erleichtern Code in kleinere, besser verwaltbare Teile. Ein Modul kann dann jederzeit importiert und flexibel verwendet werden, was bei der Erstellung wiederverwendbarer Codekomponenten hilft, die von mehreren Projekten gemeinsam genutzt werden können.

Um dies zu verstehen, betrachten Sie dieses Beispiel: Nehmen wir an, Sie haben viele Funktionen in definiert Ihr Code, der mit einer riesigen Menge an JSON-Daten funktioniert.

Schlaflosigkeit und erhöhte Angstzustände sind häufige Nebenwirkungen, wenn all diese Dinge (Funktionen, Daten, andere Logik) in einer einzigen Datei gespeichert werden.

Als cleverer Programmierer haben Sie also darüber nachgedacht, eine separate Datei für die JSON-Daten und eine separate Datei zum Speichern aller Funktionen zu erstellen. Jetzt können Sie die Daten und Funktionen einfach jederzeit importieren und entsprechend nutzen. Diese Methode erhöht die Effizienz, da sich Ihre Dateigröße drastisch verringert. Das ist das Konzept der Module!

Sehen wir uns an, wie wir unsere eigenen Module erstellen können. Dazu schreiben wir Code, in dem wir eine Funktion namens „sayHello()“ in einer Datei namens „hello.js“ definieren. Diese Funktion akzeptiert einen Namen als Parameter und gibt einfach eine Begrüßungsnachricht in der Konsole aus.

Wir importieren sie dann in eine andere Datei namens app.js und verwenden sie dort. Wie interessant, oder?? Schauen wir uns den Code an:

Dies ist der Code in der Datei „hello.js“:

function sayHello(name){
    console.log(`Hello ${name}`);}module.exports = sayHello
로그인 후 복사

Dies ist der Code in der Datei „app.js“:

const sayHello = require('./hello.js');sayHello('John');sayHello('Peter');sayHello('Rohit');
로그인 후 복사

Die Datei hello.js kann in diesem Fall als Modul bezeichnet werden. Jedes Modul verfügt über ein Objekt namens „exports“, das alle Dinge enthalten sollte, die Sie aus diesem Modul exportieren möchten, z. B. Variablen oder Funktionen. In unserem Fall definieren wir eine Funktion in der Datei „hello.js“ und exportieren sie direkt.

Die Datei „app.js“ importiert die Funktion „sayHello()“ aus „hello.js“ und speichert sie in der Variablen „sayHello“. Um etwas aus einem Modul zu importieren, verwenden wir die Methode „require()“, die den Pfad zum Modul akzeptiert. Jetzt können wir einfach die Variable aufrufen und einen Namen als Parameter übergeben. Das Ausführen des Codes in der Datei „app.js“ erzeugt die folgende Ausgabe:

Hello John
Hello Peter
Hello Rohit
로그인 후 복사

Kurze Anmerkung zu „module.exports“

Im vorherigen Abschnitt des Artikels haben wir gesehen, wie man das Modul verwendet. Exporte, aber ich hatte das Gefühl, dass es wichtig ist, etwas detaillierter zu verstehen, wie es funktioniert. Daher ist dieser Abschnitt des Artikels wie ein Mini-Tutorial, in dem wir sehen, wie wir mit module.exports eine Variable/Funktion sowie mehrere Variablen und Funktionen exportieren können. Also, fangen wir an:

module.exports ist ein spezielles Objekt in NodeJS, mit dem Sie Funktionen, Objekte oder Werte aus einem Modul exportieren können, damit andere Module darauf zugreifen und sie verwenden können. Hier ist ein Beispiel dafür, wie Sie mit „module.exports“ eine Funktion aus einem Modul exportieren:

// myModule.jsfunction myFunction() {
  console.log('Hello from myFunction!');}module.exports = myFunction;
로그인 후 복사

In diesem Beispiel definieren wir eine Funktion „myFunction“ und exportieren sie dann mit „module.exports“. Andere Module können nun dieses Modul benötigen und die exportierte Funktion verwenden:

// app.jsconst myFunction = require('./myModule');myFunction(); // logs 'Hello from myFunction!'
로그인 후 복사

Jetzt scheint alles in Ordnung zu sein und das Leben ist gut. Das Problem entsteht jedoch, wenn wir mehrere Funktionen und Variablen aus einer einzigen Datei exportieren müssen. Der Punkt ist, dass, wenn Sie „module.exports“ mehrmals in einem einzelnen Modul verwenden, der zuvor zugewiesene Wert durch den neuen ersetzt wird. Betrachten Sie diesen Code:

// module.jsfunction myFunction() {
  console.log('Hello from myFunction!');}function myFunction2() {
  console.log('Hello from myFunction2!');}// First Exportmodule.exports = myFunction;// Second Exportmodule.exports = myFunction2;
로그인 후 복사

In diesem Beispiel exportieren wir zuerst myFunction(). Aber wir überschreiben dann „module.exports“ mit einer neuen Funktion – „myFunction2()“. Infolgedessen wird nur die zweite Exportanweisung wirksam und die Funktion „myFunction()“ wird nicht exportiert.

Dieses Problem kann gelöst werden, wenn Sie „module.exports“ einem Objekt zuweisen, das alle von Ihnen verwendeten Funktionen enthält exportieren möchten, wie folgt:

// myModule.jsfunction myFunction1() {
  console.log('Hello from myFunction1!');}function myFunction2() {
  console.log('Hello from myFunction2!');}module.exports = {
  foo: 'bar',
  myFunction1: myFunction1,
  myFunction2: myFunction2};
로그인 후 복사

In diesem Beispiel exportieren wir ein Objekt mit drei Eigenschaften: foo, myFunction1 und myFunction2. Andere Module können dieses Modul erfordern und auf diese Eigenschaften zugreifen:

// app.jsconst myModule = require('./myModule');console.log(myModule.foo); // logs 'bar'myModule.myFunction1(); // logs 'Hello from myFunction1!'myModule.myFunction2(); // logs 'Hello from myFunction2!'
로그인 후 복사

To summarize, you can use module.exports as many times as you want in your NodeJS code, but you should be aware that each new assignment will replace the previous one. You should use an object to group multiple exports together.

Types Of Modules in Node

There are 2 types of modules in NodeJS:

  • Built In Modules: These are modules included in Node by default, so you can use them without installation. You just need to import them and get started.
  • External Modules: These are modules created by other developers which are not included by default. So you need to install them first before using them.

Here is an image of popular built-in modules in NodeJS and what can you do using them:

Tabular representation of the different built-in modules in NodeJS

Let's go over each of these in more detail so you can learn more about what they do.

The OS Module

The OS Module (as its name implies) provides you methods/functions with which you can get information about your Operating System.

To use this module, the first step is to import it like this:

const os = require('os');
로그인 후 복사

This is how you can use the OS Module to get information about the Operating System:?

const os = require('os')// os.uptime()const systemUptime = os.uptime();// os.userInfo()const userInfo = os.userInfo();// We will store some other information about my WindowsOS in this object:const otherInfo = {
    name: os.type(),
    release: os.release(),
    totalMem: os.totalmem(),
    freeMem: os.freemem(),}// Let's Check The Results:console.log(systemUptime);console.log(userInfo);console.log(otherInfo);
로그인 후 복사

This is the output of the above code:

Note that the output shows information about the Windows Operating System running on my system. The output could be different from yours.

521105
{
    uid: -1,
    gid: -1,
    username: 'krish',
    homedir: 'C:\\Users\\krish',
    shell: null
}
{
    name: 'Windows_NT',
    release: '10.0.22621',
    totalMem: 8215212032,
    freeMem: 1082208256
}
로그인 후 복사

Let's break down the above code and output:

  • os.uptime() tells the system uptime in seconds. This function returns the number of seconds the system has been running since it was last rebooted. If you check the first line of the output: 521105 is the number of seconds, my system has been running since it was last rebooted. Of course, it will be different for you.
  • os.userInfo() gives the information about the current user. This function returns an object with information about the current user including the user ID, group ID, username, home directory, and default shell. Below is the breakdown of the output in my case:
    {
        uid: -1,
        gid: -1,
        username: 'krish',
        homedir: 'C:\\Users\\krish',
        shell: null
    }
로그인 후 복사

The uid and gid is set to -1 in Windows, because Windows does not have the concept of user IDs like Unix-based systems. The username of my OS is krish and the home directory is 'C:\\Users\\krish'. The shell is set to null because the concept of a default shell does not exist on Windows. Windows has a default command interpreter program called Command Prompt (cmd.exe), which runs commands and manages the system.

The other methods related to OS Module like os.type(), os.release() and so on, which you saw in the above code has been used within the otherInfo object. Here is a breakdown of what these methods do:

  • os.type() - Tells the name of the Operating System
  • os.release() - Tells the release version of the Operating System
  • os.totalMem() - Tells the total amount of memory available in bytes
  • os.freeMem() - Tells the total amount of free memory available in bytes

This is the information which the above methods display about my OS:

{
    name: 'WindowsNT', // Name of my OS
    release: '10.0.22621', // Release Version of my OS
    totalMem: 8215212032, // Total Memory Available in bytes (~ 8 GB)
     freeMem: 1082208256 // Free Memory Available in bytes (~ 1 GB) }
로그인 후 복사

The PATH Module

The PATH module comes in handy while working with file and directory paths. It provides you with various methods with which you can:

  • Join path segments together
  • Tell if a path is absolute or not
  • Get the last portion/segment of a path
  • Get the file extension from a path, and much more!

You an see the PATH Module in action in the code below.

Code:

// Import 'path' module using the 'require()' method:const path = require('path')// Assigning a path to the myPath variableconst myPath = '/mnt/c/Desktop/NodeJSTut/app.js'const pathInfo = {
    fileName: path.basename(myPath),
    folderName: path.dirname(myPath),
    fileExtension: path.extname(myPath),
    absoluteOrNot: path.isAbsolute(myPath),
    detailInfo: path.parse(myPath),}// Let's See The Results:console.log(pathInfo);
로그인 후 복사

Output:

{
  fileName: 'app.js',
  folderName: '/mnt/c/Desktop/NodeJSTut',
  fileExtension: '.js',
  absoluteOrNot: true,
  detailInfo: {
    root: '/',
    dir: '/mnt/c/Desktop/NodeJSTut',
    base: 'app.js',
    ext: '.js',
    name: 'app'
  }
}
로그인 후 복사

Let's have a detailed breakdown of the above code and its output:

The first and foremost step to work with path module is to import it in the app.js file using the require() method.

Next, we are assigning a path of some file to a variable called myPath. This can be a path to any random file. For the purpose of understanding the path module, I chose this: /mnt/c/Desktop/NodeJSTut/app.js.

Using the myPath variable, we will understand the path module in detail. Let's check out the functions which this module has to offer and what can we do with it:

  • path.basename(myPath): The basename() function accepts a path and returns the last part of that path. In our case, the last part of myPath is: app.js.
  • path.dirname(myPath): The dirname() function selects the last part of the path provided to it and returns the path to it's parent's directory. In our case, since the last part of myPath is app.js. The dirname() function returns the path to the parent directory of app.js (the folder inside which app.js file lies), i.e, /mnt/c/Desktop/NodeJSTut. It can be also thought as: the dirname() function simply excludes the last part of the path provided to it and returns the leftover path.
  • path.extname(myPath): This function checks for any extension on the last part of the provided path and it returns the file extension (if it exists), otherwise it returns an empty string: ''. In our case, since the last part is app.js and a file extension exists, we get '.js' as the output.
  • path.isAbsolute(myPath): This tells whether the provided path is absolute or not. On Unix-based systems (such as macOS and Linux), an absolute path always starts with the forward slash (/). On Windows systems, an absolute path can start with a drive letter (such as C:) followed by a colon (:), or with two backslashes (\\). Since the value stored in myPath variable starts with /, therefore isAbsolute() returns true.

However, if you just change the myPath variable to this: Desktop/NodeJSTut/app.js (converting it to a relative path), isAbsolute() returns false.

  • path.parse(myPath): This function accepts a path and returns an object which contains a detailed breakdown of the path provided to it. Here is what it returns when we provide the myPath variable to it:
  • root: The root of the path (in this case, /).
  • dir: The directory of the file (in this case, /mnt/c/Desktop/NodeJSTut).
  • base: The base file name (in this case, app.js).
  • ext: The file extension (in this case, .js).
  • name: The base name of the file, without the extension (in this case, app).

Before continuing with the other functions of the path module, we need to understand something called path separator and the path structure.

You must have seen that the path to a same file looks different in different Operating Systems. For example, consider the path to a file named example.txt located in a folder called Documents on the desktop of a Windows user:

C:\Users\username\Desktop\Documents\example.txt
로그인 후 복사

On the other hand, the file path to the same file for a user on a macOS system would look like this:

/Users/username/Desktop/Documents/example.txt
로그인 후 복사

2 differences are to be noted here:

  1. Difference in path separators: In Windows, file paths use the backslash (\) as the separator between directories, while in macOS/Linux (which is a Unix-based system), file paths use the forward slash (/) as the separator.
  2. Difference in root directory of the users files: On Windows, the root directory for a user's files is commonly found at C:\Users\username, whereas on macOS and Linux, it is located at /Users/username/. While this holds true for most Windows, macOS, and Linux systems, there may be some variations in the exact location of the user's home directory based on the system's configuration.

With this in mind, let's move ahead and understand some other functions provided by the path module:

  • path.sep: sep is a variable which contains the system specific path separator. For Windows machine: console.log(path.sep) prints \ in the console while in case of macOS or Linux, path.sep returns a forward slash ( / ).
  • path.join(): The path.join() function accepts path(s) as strings. It then joins those paths using the system specific path separator and returns the joined path. For example, consider this code:
console.log(path.join('grandParentFolder', 'parentFolder', 'child.txt'))
로그인 후 복사

The above code prints different results for different Operating Systems.
In Windows, it will give this output: grandParentFolder\parentFolder\child.txt while in macOS/Linux, it will give this output: grandParentFolder/parentFolder/child.txt. Note that the difference is only in the path separators - backward slash and forward slash.

  • path.resolve(): This function works in a similar way as compared to path.join(). The path.resolve() function just joins the different paths provided to it using the system specific path separator and then appends the final output to the absolute path of the present working directory.

Suppose you are a Windows user and the absolute path to your present working directory is this: C:\Desktop\NodeJSTut, If you run this code:

console.log(path.resolve('grandParentFolder', 'parentFolder', 'child.txt'));
로그인 후 복사

You will see the following output in the console:

C:\Desktop\NodeJSTut\grandParentFolder\parentFolder\child.txt
로그인 후 복사

The same is applicable to a macOS or a Linux user. It's just the difference in the absolute path of the present working directory and the path separator.

위 내용은 NodeJS를 시작하는 방법 – 초보자를 위한 핸드북의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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