node.js Tutorial (nodejs characteristics, low knowledge, npm use, express scaffolding, etc.)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/a5252145/article/details/85294895

node.js Tutorial (nodejs characteristics, low knowledge, npm use, express scaffolding, etc.)

table of Contents

  1. Chapter 1 Introduction, three characteristics (strengths and weaknesses)
  2. Chapter warehouse project file created profiles, string parsing (serialization) and deserialization as well as some small knowledge
  3. Chapter III npm use
  4. Chapter IV express scaffolding

First, the basic things first chapter

Summary:

nodejs is based on the server operating environment js Google V8 engine development.


1.可以解析js代码,还没有一些安全级别的限制
2.提供了一些系统级别的API
	文件的读写
	进程的管理
	网络通信

Three characteristics:

1, single-threaded:

On the server side language Java, PHP or .net, etc., create a new thread for each client connection. And each thread takes about 2MB of memory. That is, in theory, a 8GB server can simultaneously connect maximum number of users is about 4000. Let Web applications to support more users, we need to increase the number of servers, and hardware costs, of course, Web applications on the rise.

Node.js is not connected to each client to create a new thread, but only one thread. When a user is connected, it triggers an internal event, through a non-blocking I / O, event-driven mechanism, so that the macro program Node.js also parallel. Use Node.js, a 8GB memory server that can handle more than 40,000 simultaneous user connections. In addition, the benefits of single-threaded, as well as the operating system is no longer fully thread creation, destruction time overhead. Harm is caused by the collapse of a user thread, the whole services have collapsed, others have collapsed.

Multi-threaded, single-threaded a comparison:

It can be seen, a single thread can also cause "concurrency" on the macro.

2, non-blocking I / O non-blocking I / O:

For example, when the acquired data to access the database, it takes some time. In a traditional single-threaded processing mechanism, after the implementation of the code to access the database, the entire thread will pause and wait for the database to return the results in order to execute the code behind. In other words, I / O block the execution of the code, which greatly reduces the efficiency of the implementation of the program.

Since Node.js is adopted after the non-blocking I / O mechanism, so the code access to the database is performed, immediately behind the code is executed instead, the database returns the results of the processing code in the callback function, thereby improving the efficiency of the program.

When an I / O is finished, the form will be event notification thread of execution I / O operations and thread callback function for this event. To handle asynchronous I / O, thread must have an event loop, constantly checking there are no pending events, to be addressed in turn.

Blocking mode, a thread can only handle one task, in order to improve the throughput must be multi-threaded. The non-blocking mode, a thread always perform computing operations, the thread CPU core utilization is always 100%. So, this is a particularly philosophical solutions: its people, but a lot of people idle; your life is not like a person, Kill working children.

2, event-driven event-driven:

In Node, the client requests to establish a connection, to submit data and other acts, will trigger the corresponding event. In Node, in one moment, you can only execute a callback event, but an event callback function to perform in the middle, you can turn to other events (for example, another new user is connected), and then return to continue with the original event callback function, this processing mechanism, known as the "event loop" mechanism.

Node.js is the underlying C ++ (V8 is written in C ++). Underlying code, the event queue for nearly half are constructed callback queue. Event-driven scheduling server to complete the task, which is to think of the devil. Dancing on the tip, with a thread, take up the mission to deal with a lot of tasks.

总结:

  1. The benefits of single-threaded, single-threaded, reduced memory overhead, operating system, memory paging. If one thing has entered, but was I / O blocked, so this thread is blocked.
  2. Non-blocking I / O, not Shadeng I / O statement ends, but will execute the statements that follow. Non-blocking will be able to solve the problem yet? For example, the implementation of the red business, the implementation process, Xiaogang's I / O completion callback, at this time how to do? ?
  3. Event mechanism, the event loop, whether a new user's request, or the old user I / O completion, all the way to join the event will be an event loop, waiting to be scheduled.
  4. Said that the three features, in fact, is a feature, not to leave anyone, they do not turn up to play. Node.js like Stingy restaurateur, just hire a waiter, serving a lot of people. As a result, the efficiency is higher than many attendants. Node.js All I / O are asynchronous callback, the callback function sets.

Second, Chapter II project

Warehouse creation process

  1. Environmental npm
    npm init -y
  2. github site shows something,
    create a new file README.md
  3. .gitignore file represents something ignored

Parsing a string serialization :()
querystring.stringify ({name: "Xiaoming", Cour: [ 'NiHao', 'Hello'], form: ""})
after parsing End:

'name=xiaoming&cour=nihao&cour=hello&form='

& Default as connectors.
E.g:

 querystring.stringify({name:"xiaoming",cour:['nihao','hello'],form:""},',')

After the conversion:

'name=xiaoming,cour=nihao,cour=hello,form='

: Connection if needed, and then append a:

Deserialization

querystring.parse('name=xiaoming,cour=nihao,cour=hello,form=')

After after deserialization:

{ name: 'xiaoming,cour=nihao,cour=hello,form=' }

Especially funny but the image of the picture

Third, the use of Chapter III npm

npm安装模块

【npm install xxx】利用 npm 安装xxx模块到当前命令行所在目录;
【npm install -g xxx】利用npm安装全局模块xxx;

本地安装时将模块写入package.json中:

【npm install xxx】安装但不写入package.json;
【npm install xxx --save】 安装并写入package.json的"dependencies"中;
【npm install xxx --save-dev】安装并写入package.json的"devDependencies"中。

npm 删除模块

【npm uninstall xxx】删除xxx模块;
【npm uninstall -g xxx】删除全局模块xxx;

Four, express the use of scaffolding

installation

  1. Global express-generator mounted scaffolding
    cnpm install express-generator -g

  2. And vue-cli scaffolding, you can create a project with a simple command, express well.
    First we go to the appropriate directory, and then execute the following code cmd (demo project name, can be replaced by others)

    express demo
    

    At this point you can see more than a new directory folder demo

  3. Step 3: Install rely
    cd demo into the demo folder
    cnpm install

  4. npm run start start the project
    appears node ./bin/www for success URL: HTTP: // localhost: 3000 /

bin:项目核心文件夹,内部有一个www文件,用于创建express实例(修改端口在这里);
node_modules:模块文件夹,本项目用到的全部依赖都在里面,相当于一个个的插件(自动生成,不用修改);
public:静态资源文件夹,主要存放css、html、js和图片等(基本不用);
routes:路由文件夹,放路由逻辑,这是我们核心部分;
views:视图文件夹,主要是一些视图文件(基本不用);
app.js:入口文件,相当于vue和react下的main.js,这也是我们的核心部分(和www文件类似,一个是逻辑入口,一个是物理入口,只不过www文件我们一般不用改,而app.js则是经常变动);
package.json:项目文件,存放项目信息;

bin/www文件主要是创建并启动http服务,一般来说我们是不用修改代码的。但是如果端口冲突无法正常启动,那就需要来稍微修改一下了。该项目的默认端口是3000,如果冲突,直接在第15行修改成其他端口就可以了

app.js下:

// 引入路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

// 配置路由
app.use('/', indexRouter);
app.use('/users', usersRouter);

app.js可以理解成入口文件,里面主要是加载创建express实例,然后配置路由(其实还有更重要的拦截器、也可以叫过滤器,后面再说.

配置路由那两句话表示:

我的路径是http:localhost:3000/,那么我使用indexRouter路由;
如果我的路径是http:localhost:3000/users,那么我使用usesRouter路由

index.js

/* indexRouter路由具体API*/
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

routes/index.js是路由的具体实现,这个文件最终导出一个express.router实例,这里面的代码意思是说,在当前路由下,如果路径是“/”,那么返回index视图。其中req为请求,res为响应,通过req可以拿到请求参数和请求头等信息,通过res可以执行响应。
在本系统下,基本不会用到视图,上面的res.render()一般改成res.send()。如routes/user.js

res.send('index', { title: 'Express' });

To create a new routing API, in app.js, import routes, configure routing, create routes in test.js

//app.js下
// 引入路由
var testRouter = require('./routes/test');
// 配置路由
app.use('/test', testRouter);


//test.js下
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send("你好,我是测试!");
});
module.exports = router;

Such browser to open http: // localhost: 3000 / test you can see the return "Hello, I was testing!."
I'm sorry to tell you, express-generator does not support hot load, you may have to restart it.

Thermal loading module mounting nodemon

Step 1: Install nodemon

cnpm install nodemon --save-dev

Plus -save-dev or -save but a good habit, which can depend on the project situation in the project design document, the time share project provides package.json it.

Step Two: Configure nodemon

How to add your own commands in the script node project it? Actually very simple, you need to modify scripts at package.json on it (is universal, the same in other scaffolding), we add the following command:

"dev": "nodemon ./bin/www"
"scripts": {
    "start": "node ./bin/www",
    "dev": "nodemon ./bin/www"
  },

This time run npm run'll notice a dev console input npm run and start to dev

So our page will and code synchronization, and do not need to shut down the server each time to manually start

How to develop a project, reference blog:

https://www.jianshu.com/p/ebef9ffb7851

Guess you like

Origin blog.csdn.net/a5252145/article/details/85294895