搜尋
首頁web前端js教程如何開始使用 NodeJS – 初學者手冊

如何開始使用 NodeJS – 初學者手冊

Oct 09, 2024 am 10:44 AM
nodejsnodejs開發

What is Node?

Node is an environment in which you can run JavaScript code "Outside the web browser". Node be like – "Hey y'all, you give your JS code to me and I'll run it 😎". It uses Google's V8 Engine to convert the JavaScript code to Machine Code.

Since Node runs JavaScript code outside the web browser, this means that it doesn't have access to certain features that are only available in the browser, like the DOM or the window object or even the localStorage.

This means that at any point in your code, you can't type in document.querySelector() or alert() as these will produce errors (This is what is shown in the below image).

Remember: Node is meant for server-side programming, while those browser features are meant for client-side programming.

Node does not know about Browser API's

Front-end folks don't be sad – there's more to it! Node provides you with lots of API's and Modules with which you can perform a variety of operations like File Handling, Creating Servers, and much more. Before diving into the NodeJS, first let's install it in our machine.

How to Install NodeJS

Installing NodeJS is straightforward. If you already have Node installed in your machine, you can skip this section. If not, then follow along.

Here are the steps to download NodeJS on your machine:

  1. Navigate to https://nodejs.org/
  2. Download the LTS Version of NodeJS for your operating system
  3. Run the installer and follow the installation wizard. Simply answer Yes to all the questions.
  4. Once the installation is complete, open a new terminal or command prompt window and run the following command to verify that NodeJS is installed correctly: node -v. If you see the version of NodeJS printed in your terminal, Congratulations! You have now successfully installed NodeJS on your machine.

Note: If you encounter any issues during the installation process, you can refer to the official NodeJS documentation for more detailed instructions and troubleshooting tips.

Global Variables

Let's start this article by learning about some variables present in NodeJS called Global Variables. These are basically variables which store some data and can be accessed from anywhere in your code – doesn't matter how deeply nested the code is.

You should know about these commonly used Global variables:

  • __dirname: This variable stores the path to the current working directory.
  • __filename: This variable stores the path to the current working file.

Let's use them and see what value they contain. For this, let's create a new folder called NodeJSTut in your Desktop and open it up with your favorite text editor (In the entire tutorial, we will be using VS Code). Create a new file called app.js and open up a new integrated VS Code Terminal.

Paste the following code in the app.js file and save it:

// __dirname Global Variableconsole.log(__dirname);// __filename Global Variableconsole.log(__filename);

To run this code using Node, type in the following command in the terminal and press Enter: node app.js. You will see the absolute path to the present working directory and the path to the current file is printed in the terminal. This is what the output looks like in my case:

C:\Desktop\NodeJSTut
C:\Desktop\NodeJSTut\app.js

You can go ahead and create your own global variables which can be accessed from anywhere in your code. You can do so, like this:

// Define a global variable in NodeJSglobal.myVariable = 'Hello World';// Access the global variableconsole.log(myVariable); // Output: Hello World

Modules in NodeJS

In Node.js, a module is essentially a reusable block of code that can be used to perform a specific set of tasks or provide a specific functionality. A module can contain variables, functions, classes, objects, or any other code that can be used to accomplish a particular task or set of tasks.

The primary purpose of using modules in Node.js is to help organize code into smaller, more manageable pieces. A modules can then be imported at any time and used flexibly which helps in creating reusable code components that can be shared across multiple projects.

To understand this, consider this example: Let's say you have defined lots of functions in your code that works with a huge volume of JSON data.

Losing your sleep and increased anxiety levels are common side effects of keeping all this stuff (functions   data   some other logic) in one single file.

So you, being a clever programmer, thought of making a separate file for the JSON data and a separate file for storing all the functions. Now, you can simply import the data and the functions whenever you want and use them accordingly. This method increases efficiency as your file size reduces drastically. This is the concept of modules!

Let's see how we can make our own modules. For this, we are going to write some code where we will be defining a function called sayHello() in a file called hello.js. This function will accept a name as the parameter and simply print a greeting message in the console.

We will then import it in another file called app.js and use it there. How interesting, right 😂? Let's check out the code:

This is the code in hello.js file:

function sayHello(name){
    console.log(`Hello ${name}`);}module.exports = sayHello

This is the code in app.js file:

const sayHello = require('./hello.js');sayHello('John');sayHello('Peter');sayHello('Rohit');

The file hello.js can be called the module in this case. Every module has an object called exports which should contain all the stuff you want to export from this module like variables or functions. In our case, we are defining a function in the hello.js file and directly exporting it.

The app.js file imports the sayHello() function from hello.js and stores it in the sayHello variable. To import something from a module, we use the require() method which accepts the path to the module. Now we can simply invoke the variable and pass a name as a parameter. Running the code in app.js file will produce the following output:

Hello John
Hello Peter
Hello Rohit

Short Note on module.exports

In the previous section of the article, we saw how to use module.exports but I felt that it is important to understand how it works in a bit more detail. Hence, this section of the article is like a mini tutorial where we will see how we can export one variable/function as well as multiple variables and functions using module.exports. So, Let's get started:

module.exports is a special object in NodeJS that allows you to export functions, objects, or values from a module, so that other modules can access and use them. Here's an example of how to use module.exports to export a function from a module:

// myModule.jsfunction myFunction() {
  console.log('Hello from myFunction!');}module.exports = myFunction;

In this example, we define a function myFunction and then export it using module.exports. Other modules can now require this module and use the exported function:

// app.jsconst myFunction = require('./myModule');myFunction(); // logs 'Hello from myFunction!'

Everything seems fine now and life is good. But the problem arises when we have to export multiple functions and variables from a single file. The point is when you use module.exports multiple times in a single module, it will replace the previously assigned value with the new one. Consider this 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 this example, we first export myFunction(). But we then overwrite module.exports with a new function - myFunction2(). As a result, only the second export statement will take effect, and the myFunction() function will not be exported.

This problem can be solved if you assign module.exports to an object which contains all the functions you want to export, like this:

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

In this example, we export an object with three properties: foo, myFunction1, and myFunction2. Other modules can require this module and access these properties:

// 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript,C和瀏覽器之間的關係JavaScript,C和瀏覽器之間的關係May 01, 2025 am 12:06 AM

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr

node.js流帶打字稿node.js流帶打字稿Apr 30, 2025 am 08:22 AM

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python vs. JavaScript:性能和效率注意事項Python vs. JavaScript:性能和效率注意事項Apr 30, 2025 am 12:08 AM

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript的起源:探索其實施語言JavaScript的起源:探索其實施語言Apr 29, 2025 am 12:51 AM

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

幕後:什麼語言能力JavaScript?幕後:什麼語言能力JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

Python和JavaScript的未來:趨勢和預測Python和JavaScript的未來:趨勢和預測Apr 27, 2025 am 12:21 AM

Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。

Python vs. JavaScript:開發環境和工具Python vs. JavaScript:開發環境和工具Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

JavaScript是用C編寫的嗎?檢查證據JavaScript是用C編寫的嗎?檢查證據Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。