search
HomeWeb Front-endJS TutorialGetting started with nodejs tutorial_node.js

Foreword

If we don’t learn nodeJs, we will be old... When the HTML5 wave hit, many ancestors started the journey of NodeJs, and at that time I was still doing server-side programs
Later, I switched to front-end, and the distance between me and the echelon is already very big. Because I know server-side languages ​​and have been working for a long time, I have only started to learn NodeJs and move towards a complete front-end
The plan to learn NodeJs this time is:
① 1-2 weeks to learn basic knowledge
② Develop a simple project in about 1 week
③ Use NodeJs to develop a set of tools for mobile terminal debugging
④ Packaging related (this may be a bit far away)

NodeJs Features

① Asynchronous
From file reading to network requests, NodeJs is completed asynchronously, and callback functions play an important role. Node is leading in terms of programming model

② Event callback
Event callbacks make programs lightweight, but the details are still up to the programmer. However, the callback function is actually quite difficult to read

③ Single thread
Node is single-threaded. If it were multi-threaded, the language would be too deep. It would be annoying to ask about in-process communication, but there are no deadlocks or other problems with threads
But there is a problem related to performance, because multi-core cannot be used;

Module mechanism/CommonJs

We used to do server-side development. If the code is not well organized, later maintenance will be very difficult, so there is MVC and three-tier architecture
Now the business logic of the front-end is gradually moving closer to the back-end. As far as single-page applications are concerned, it has surpassed the program logic of the back-end
The continuous increase in page views will bring about a surge in the amount of js code. How to manage our front-end code well has become a problem, so requireJs appeared...
PS: This paragraph has nothing to do with nodeJs...
JavaScript does not have a modular system, so CommonJs was proposed to give js the basis for developing large-scale applications

Module reference

If we want to reference a module, such as mathematical calculations:

var math = require('math');

Module definition

If we want to define our own module, we can do this

Copy code The code is as follows:

exports.add = function () {
Return sum;
}

If this function is defined in math, it can be used

math.add();

Module ID

The module identifier is the parameter passed to require. It needs to be named in camel case and points to a file path. This is very similar to requireJS

Module implementation

Module implementation in Node is divided into two categories, one is the system-level core module, and the other is the file module written by the user
The core modules are translated into binary files during the compilation process. After the Node process is started, some core modules will be loaded directly into the memory (file location, compilation and execution)
The file module needs to be loaded dynamically, which is relatively slow
But once loaded, those files will be cached, and the cached files (compiled files) will be read when they are introduced again
Let’s go a bit further here. When we use underscore, we will compile Html to form a template function (it is really just a function). In fact, this can be used for caching
Save the compiled function before deploying the project and remove the html template file (the optimization effect is unknown)

In node, each module is an object:

Copy code The code is as follows:

function Module(id, parent) {
this.id = id;
this.exports = {};
//parent is a keyword and should not be used indiscriminately
This.parent = parent;
if (parent && parent.children) {
parent.children.push(this);
}
this.filename = null;
this.loaded = false;
this.children = [];
}

The last stage of introducing file modules during compilation and execution. After locating the specific file, node will create a new module object, then load and compile according to the path
Each successfully compiled module will cache its file path as an index on Module._cache

Each module file has three variables: require, exports, and module, but they are not defined in the file (the same is true for the __filename__ and __dirname__ variables)
In fact, during the compilation process, Node wraps the contents of the javascript file head and tail (equivalent to passing the custom function into the window)

Copy code The code is as follows:

(function (exports, require, module, __filename__, __dirname__) {
var math = require('math');
exports.area = function (radius) {
Return '';
};
});

In this way, the modules are isolated and will not affect each other. This is somewhat similar to the compilation of underscore...

Packages and NPM

Node organizes its own core modules, so third-party file modules can be written and used in an orderly manner, but in third-party modules, modules are still hashed in various places
They cannot directly reference each other. Module outsourcing and NPM are a mechanism to establish connections
PS: Many modules will form a package. The concept of this package is similar to the concept of java package, so the concept of #assembly should be similar

After decompressing a package structure, several files will be formed:
① package.json description file
② bin executable binary directory
③ lib javascript code directory
④ doc document (nearly none)
⑤ test demo

The above are some of the specifications of the CommonJS package, but we can understand it a little bit (for beginners). NPM needs to be mastered. With the help of NPM, we can skillfully install the management package

Install dependency packages

Installing dependency packages is a common method:

npm install express
After execution, the node_modules directory will be created in the current directory, and then the express directory will be created under it...
PS: express is a popular web development framework on NodeJs, which helps us quickly develop a web application
It can be called after the installation is completed:

Copy code The code is as follows:

var express = require('express');

Conclusion

This section ends briefly, and our actual project process will gradually deepen later

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.