Home Web Front-end JS Tutorial Getting started with nodejs tutorial_node.js

Getting started with nodejs tutorial_node.js

May 16, 2016 pm 04:30 PM
nodejs getting Started

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 of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Aug 01, 2024 pm 03:28 PM

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award Jun 20, 2024 pm 05:43 PM

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts Jul 24, 2024 pm 08:13 PM

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days Aug 07, 2024 pm 10:53 PM

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Jul 11, 2024 pm 01:53 PM

Retrieval-augmented generation (RAG) is a technique that uses retrieval to boost language models. Specifically, before a language model generates an answer, it retrieves relevant information from an extensive document database and then uses this information to guide the generation process. This technology can greatly improve the accuracy and relevance of content, effectively alleviate the problem of hallucinations, increase the speed of knowledge update, and enhance the traceability of content generation. RAG is undoubtedly one of the most exciting areas of artificial intelligence research. For more details about RAG, please refer to the column article on this site "What are the new developments in RAG, which specializes in making up for the shortcomings of large models?" This review explains it clearly." But RAG is not perfect, and users often encounter some "pain points" when using it. Recently, NVIDIA’s advanced generative AI solution

See all articles