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.
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:
- Navigate to https://nodejs.org/
- Download the LTS Version of NodeJS for your operating system
- Run the installer and follow the installation wizard. Simply answer Yes to all the questions.
- 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:
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:
- 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.
- 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中文网其他相关文章!

Node.js擅长于高效I/O,这在很大程度上要归功于流。 流媒体汇总处理数据,避免内存过载 - 大型文件,网络任务和实时应用程序的理想。将流与打字稿的类型安全结合起来创建POWE

Python和JavaScript在性能和效率方面的差异主要体现在:1)Python作为解释型语言,运行速度较慢,但开发效率高,适合快速原型开发;2)JavaScript在浏览器中受限于单线程,但在Node.js中可利用多线程和异步I/O提升性能,两者在实际项目中各有优势。

JavaScript起源于1995年,由布兰登·艾克创造,实现语言为C语言。1.C语言为JavaScript提供了高性能和系统级编程能力。2.JavaScript的内存管理和性能优化依赖于C语言。3.C语言的跨平台特性帮助JavaScript在不同操作系统上高效运行。

JavaScript在浏览器和Node.js环境中运行,依赖JavaScript引擎解析和执行代码。1)解析阶段生成抽象语法树(AST);2)编译阶段将AST转换为字节码或机器码;3)执行阶段执行编译后的代码。

Python和JavaScript的未来趋势包括:1.Python将巩固在科学计算和AI领域的地位,2.JavaScript将推动Web技术发展,3.跨平台开发将成为热门,4.性能优化将是重点。两者都将继续在各自领域扩展应用场景,并在性能上有更多突破。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

是的,JavaScript的引擎核心是用C语言编写的。1)C语言提供了高效性能和底层控制,适合JavaScript引擎的开发。2)以V8引擎为例,其核心用C 编写,结合了C的效率和面向对象特性。3)JavaScript引擎的工作原理包括解析、编译和执行,C语言在这些过程中发挥关键作用。

JavaScript是现代网站的核心,因为它增强了网页的交互性和动态性。1)它允许在不刷新页面的情况下改变内容,2)通过DOMAPI操作网页,3)支持复杂的交互效果如动画和拖放,4)优化性能和最佳实践提高用户体验。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1
好用且免费的代码编辑器

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中