Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.
A Node.js app is run in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.
When Node.js needs to perform an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.
In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.
中文意思含义如下:
Node.js是一个开源的、跨平台的JavaScript运行时环境。它是一个流行的工具,几乎适用于任何类型的项目!
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,位于浏览器之外,这使得Node.js具有非常好的性能。 一个Node.js应用程序运行在单个线程中,不会为每个请求单独创建新的线程。
Node.js在其标准库中提供了一组异步I/O基元来防止JavaScript代码被阻塞,通常,Node.js中的库是使用非阻塞范型编写的,这使得阻塞行为成为一种例外而非常态。
当Node.js需要执行I/O操作时,比如从网络中读取数据、访问数据库或文件系统,Node.js将在响应返回时恢复这些操作。而不是阻塞线程和浪费CPU等待周期。
这允许Node.js在一个服务器上处理数千个并发连接,而不会带来管理线程并发的负担,因为线程并发可能是一个重要的bug来源。
Node.js有一个独特的优势,因为数百万为浏览器编写JavaScript的前端开发人员现在能够编写服务器端代码和客户端代码,而不需要学习一门完全不同的语言。
注:这句话表明学会了node.js就意味着可以成为全栈工程师 在Node.js中,新的ECMAScript标准可以毫无问题地使用,因为您不必等待所有用户更新他们的浏览器--你可以通过更改Node.js版本来决定使用哪个ECMAScript版本,您还可以通过运行带标志的Node.js来启用特定的实验特性。
我们再来看百度百科对nodejs的解释Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。 Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型。 [1]
Node 是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为与PHP、Python、Perl、Ruby 等服务端语言平起平坐的脚本语言。 [2] 发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装。
Node对一些特殊用例进行优化,提供替代的API,使得V8在非浏览器环境下运行得更好。V8引擎执行Javascript的速度非常快,性能非常好。Node是一个基于Chrome JavaScript运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node 使用事件驱动, 非阻塞I/O 模型而得以轻量和高效,非常适合在分布式设备上运行数据密集型的实时应用。
我的理解nodejs就是一个服务端JavaScript 运行环境,借助这个环境,我们不用依赖客户端的浏览器来解释执行JavaScript脚本,而是直接在服务端环境中解释执行,这样可以避免很多浏览器版本兼容性问题;再有,我们可以通过JavaScript这门开发语言同时实现服务端和客户端的功能逻辑,简化了开发流程和人员、技能配置树,降低了项目开发、维护成本。
2. 怎么实现nodejs环境?实现一个nodejs也就是安装nodejs这个软件,在介绍如下几种平台的安装方式之前,我们需要了解一下nvm。
什么是nvm?官方介绍如下:
nvm is a version manager for node.js, designed to be installed per-user, and invoked per-shell. nvm works on any POSIX-compliant shell (sh, dash, ksh, zsh, bash), in particular on these platforms: unix, macOS, and windows WSL.
中文含义:
nvm是一个node.js版本管理器,它可以按照单独的用户安装,使用不同的shell来执行。nvm可以工作在任何与posix兼容的shell
中,例如sh、bash、ksh、zsh、dash等,尤其是unix、macOS以及Windows这三类平台。
参考文档:https://github.com/nvm-sh/nvm#about
macOS参照官方介绍
On macOS, Homebrew is the de-facto standard, and - once installed - allows to install Node.js very easily, by running this command in the CLI:
brew install node Windows如果项目已经说明仅依赖某一个特定版本的nodejs环境,那么可以直接去官网下载安装包进行安装,安装过程连续点“下一步”即可,网上有很多安装教程,这里就不在展示;我们这里主要展示通过nvm来管理不同版本的nodejs,因为某些项目可能需要用到多个不同的nodejs版本,所以用nvm来管理nodejs版本显得非常便捷。
参考文档:https://github.com/coreybutler/nvm-windows
在文档中,我们可以看到nvm的安装流程如下
Uninstall existing node
Please note, you need to uninstall any existing versions of node.js before installing NVM for Windows. Also delete any existing nodejs installation directories (e.g., "C:Program Filesnodejs") that might remain. NVM's generated symlink will not overwrite an existing (even empty) installation directory.
Uninstall existing npm
You should also delete the existing npm install location (e.g. "C:Users<user>AppDataRoamingnpm"), so that the nvm install location will be correctly used instead. Backup the global npmrc config (e.g. C:Users<user>AppDataRoamingnpmetcnpmrc), if you have some important settings there, or copy the settings to the user config C:Users<user>.npmrc.
Install nvm-windows
nvm-windows comes with an installer (and uninstaller), because getting it should be easy.
Reinstall any global utilities
After install, reinstalling global utilities (e.g. gulp) will have to be done for each installed version of node:
nvm use 4.4.0 npm install gulp-cli -g nvm use 0.10.33 npm install gulp-cli -g文档中描述的nvm安装流程是: 卸载已有nodejs
卸载npm
安装nvm-windows
为每个已经安装的nodejs版本重新安装全局实用程序
下面我们按照这个流程来操作
卸载现有的nodejs卸载npm,由于我们之前安装的npm是包含在nodejs中的,所以已经随nodejs一起删除 安装nvm-windows下载安装包:https://github.com/coreybutler/nvm-windows/releases
拷贝压缩包到nodejs安装目录的nvm目录下
解压缩并运行安装程序
为每个已经安装的nodejs版本重新安装全局实用程序我们这里不需要做这个操作
安装成功之后,我们可以查看一下nvm的使用方式,文档中的使用方式介绍如下
Usage
nvm-windows runs in an Admin shell. You'll need to start powershell or Command Prompt as Administrator to use nvm-windows
NVM for Windows is a command line tool. Simply type nvm in the console for help. The basic commands are:
nvm arch [32|64]: Show if node is running in 32 or 64 bit mode. Specify 32 or 64 to override the default architecture.
nvm install <version> [arch]: The version can be a node.js version or "latest" for the latest stable version. Optionally specify whether to install the 32 or 64 bit version (defaults to system arch). Set [arch] to "all" to install 32 AND 64 bit versions.
nvm list [available]: List the node.js installations. Type available at the end to show a list of versions available for download.
nvm on: Enable node.js version management.
nvm off: Disable node.js version management (does not uninstall anything).
nvm proxy [url]: Set a proxy to use for downloads. Leave [url] blank to see the current proxy. Set [url] to "none" to remove the proxy.
nvm uninstall <version>: Uninstall a specific version.
nvm use <version> [arch]: Switch to use the specified version. Optionally specify 32/64bit architecture. nvm use <arch> will continue using the selected version, but switch to 32/64 bit mode based on the value supplied to <arch>. For information about using use in a specific directory (or using .nvmrc), please refer to issue #16.
nvm root <path>: Set the directory where nvm should store different versions of node.js. If <path> is not set, the current root will be displayed.
nvm version: Displays the current running version of NVM for Windows.
nvm node_mirror <node_mirror_url>: Set the node mirror.People in China can use https://npm.taobao.org/mirrors/node/
nvm npm_mirror <npm_mirror_url>: Set the npm mirror.People in China can use https://npm.taobao.org/mirrors/npm/
就说,我们可以通过powershell和Command命令行来调用nvm-windows,它本身就是一个命令行工具,我们直接在命令行中键入"nvm"可以查看当前nvm的版本号及相关用法命令
C:Userszhang>nvm Running version 1.1.7. Usage: nvm arch : Show if node is running in 32 or 64 bit mode. nvm install <version> [arch] : The version can be a node.js version or "latest" for the latest stable version. Optionally specify whether to install the 32 or 64 bit version (defaults to system arch). Set [arch] to "all" to install 32 AND 64 bit versions. Add --insecure to the end of this command to bypass SSL validation of the remote download server. nvm list [available] : List the node.js installations. Type "available" at the end to see what can be installed. Aliased as ls. nvm on : Enable node.js version management. nvm off : Disable node.js version management. nvm proxy [url] : Set a proxy to use for downloads. Leave [url] blank to see the current proxy. Set [url] to "none" to remove the proxy. nvm node_mirror [url] : Set the node mirror. Defaults to https://nodejs.org/dist/. Leave [url] blank to use default url. nvm npm_mirror [url] : Set the npm mirror. Defaults to https://github.com/npm/cli/archive/. Leave [url] blank to default url. nvm uninstall <version> : The version must be a specific version. nvm use [version] [arch] : Switch to use the specified version. Optionally specify 32/64bit architecture. nvm use <arch> will continue using the selected version, but switch to 32/64 bit mode. nvm root [path] : Set the directory where nvm should store different versions of node.js. If <path> is not set, the current root will be displayed. nvm version : Displays the current running version of nvm for Windows. Aliased as v.查看当前已经安装了的nodejs版本
C:Userszhang>nvm list No installations recognized.下面我们来安装nodejs Latest LTS Version:12.16.3
C:Usersasqzhang>nvm install 12.16.3 Downloading node.js version 12.16.3 (64-bit)... Complete Creating F:nodejsnvmnvmtemp Downloading npm version 6.14.4... Complete Installing npm v6.14.4... Installation complete. If you want to use this version, type nvm use 12.16.3使用此版本并分别查看node.js和npm的版本号
C:Userszhang>nvm use 12.16.3 Now using node v12.16.3 (64-bit) C:Userszhang>node -v v12.16.3 C:Userszhang>npm -v 6.14.4Linux与Windows平台一致,如果你是期望直接安装某个版本的nodejs而不涉及到多版本nodejs切换,可参考如下操作例如,我这里有台Centos发行版本7.6的服务器
[root@zhang ~]# cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core)查看未安装nodejs软件
[root@zhang ~]# rpm -qa | grep node [root@zhang ~]#此时如果我想快速地实现一个nodejs环境,那么很简单,我只需要通过如下方式即可安装nodejs软件
下载nodejs压缩文件
[root@zhang data]# wget https://nodejs.org/dist/v12.16.3/node-v12.16.3-linux-x64.tar.gz解压缩
[root@zhang data]# tar -zxvf node-v12.16.3-linux-x64.tar.gz > /dev/null[root@zhang node-v12.16.3-linux-x64]# ls -lh bin/ total 45M -rwxr-xr-x 1 1001 1001 45M Apr 28 17:54 node lrwxrwxrwx 1 1001 1001 38 Apr 28 17:54 npm -> ../lib/node_modules/npm/bin/npm-cli.js lrwxrwxrwx 1 1001 1001 38 Apr 28 17:54 npx -> ../lib/node_modules/npm/bin/npx-cli.js可以看到node的执行文件和npm的执行文件入口都在bin目录下,我们为node和npm各自创建一个ln软连接到软件安装目录"/usr/local/bin"下(Path环境变量路径)
[root@zhang node-v12.16.3-linux-x64]# ln -s /data/node-v12.16.3-linux-x64/bin/node /usr/local/bin [root@zhang node-v12.16.3-linux-x64]# ln -s /data/node-v12.16.3-linux-x64/bin/npm /usr/local/bin查看nodejs、npm的版本号
[root@zhang node-v12.16.3-linux-x64]# cd ~ [root@zhang ~]# [root@zhang ~]# node -v v12.16.3 [root@zhang ~]# npm -v 6.14.4但是大多数时候,我们还是需要安装nvm来管理多版本nodejs,因此可以参考如下操作Linux中的nvm参考文档是:https://github.com/nvm-sh/nvm/blob/master/README.md
文档中的安装描述是
Install & Update Script
To install or update nvm, you should run the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bashwget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bashRunning either of the above commands downloads a script and runs it. The script clones the nvm repository to ~/.nvm, and attempts to add the source lines from the snippet below to the correct profile file (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc).
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm文档告诉我们,安装nvm是通过脚本方式实现的,脚本可以通过直接下载到服务端手动运行,也可以通过如下命令下载运行,其实无论哪种方式都需要安装git客户端且版本要在2.0以上
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash 我们这里介绍第二种方式:
安装2.0版本以上的git客户端,如果你的系统是Centos发行版的,可以参考下面的安装演示;如果是其他发行版,可以参考git官网指引,通过简单的命令即可安装
非Centos发行版系统安装方式参考Git官方文档下载指引
Centos发行版系统(这里是Centos6.9)安装流程如下:
安装Git依赖包:
检查是否安装"Development Tools"软件组,若未安装则执行安装命令
[root@zhang tmp]# yum grouplist | grep "Development Tools" [root@zhang tmp]# [root@zhang yum.repos.d]# yum groupinstall "Development Tools" -y [root@zhang yum.repos.d]# yum grouplist | grep "Development tools" Development tools安装其他软件包(如果已安装了会提示已安装)
yum install zlib-devel -y yum install perl-ExtUtils-MakeMaker -y yum install asciidoc -y yum install xmlto -y yum install openssl-devel -y yum install gcc -y yum install curl-devel -y yum install expat-devel -y yum install gettext-devel -y卸载现有Git
[root@zhang git-2.0.5]# yum remove git -y下载2.0版本的Git客户端,如果下载慢,可以用网速较好的机器下载后再上传到服务器中,下载后解压
[root@zhang tmp]# wget https://www.kernel.org/pub/software/scm/git/git-2.0.5.tar.gz[root@zhang tmp]# ls -lh | grep git drwxrwxr-x 19 root root 12K Dec 19 2014 git-2.0.5 -rw-r--r-- 1 root root 4.7M Dec 19 2014 git-2.0.5.tar.gz进入解压目录,三步编译安装法安装
软件配置与检查
[root@zhang git-2.0.5]# ./configure --prefix=/usr/local/git编译成二进制文件
[root@zhang git-2.0.5]# make安装编译后的文件到指定目录
[root@zhang git-2.0.5]# make install将Git的运行程序路径配置到全局环境变量中(路径为"/usr/local/git/bin")
[root@zhang git-2.0.5]# vi /etc/profile[root@zhang git-2.0.5]# cat /etc/profile | grep "export PATH=" export PATH=/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/mysql/bin:$PATH:/usr/local/git/bin使得修改生效
[root@zhang git-2.0.5]# source /etc/profile [root@zhang git-2.0.5]#查看git版本号
[root@zhang git-2.0.5]# git --version git version 2.0.5安装nvm
参考官方文档:https://github.com/nvm-sh/nvm/blob/master/README.md
[root@zhang git-2.0.5]# curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 13527 100 13527 0 0 5385 0 0:00:02 0:00:02 --:--:-- 12131 => Downloading nvm from git to '/root/.nvm' => Cloning into '/root/.nvm'... remote: Enumerating objects: 290, done. remote: Counting objects: 100% (290/290), done. remote: Compressing objects: 100% (257/257), done. remote: Total 290 (delta 35), reused 97 (delta 20), pack-reused 0 Receiving objects: 100% (290/290), 163.27 KiB | 8.00 KiB/s, done. Resolving deltas: 100% (35/35), done. Checking connectivity... done. => Compressing and cleaning up git repository => Appending nvm source string to /root/.bashrc => Appending bash_completion source string to /root/.bashrc => Close and reopen your terminal to start using nvm or run the following to use it now: export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion" # This loads nvm bash_completion在当前用户的环境变量配置文件"~/.bash_profile"或者全局环境变量配置文件"/etc/profile"中加入如下内容
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
[root@zhang ~]# vi ~/.bash_profile [root@zhang ~]# tail -2f ~/.bash_profile export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"重载环境变量
source ~/.bash_profile测试nvm是否安装成功
[root@zhang ~]# nvm --version 0.35.3 [root@zhang ~]#安装Node.js 7.10.1 版本及以上
[root@zhang ~]# nvm install v10.6.0 Downloading and installing node v10.6.0... Downloading https://nodejs.org/dist/v10.6.0/node-v10.6.0-linux-x64.tar.xz... ######################################################################## 100.0% Computing checksum with sha256sum Checksums matched! Now using node v10.6.0 (npm v6.1.0) [root@zhang ~]# node -v v10.6.0 [root@zhang ~]# npm -v 6.1.0 3.npm是什么?官方介绍文档:https://docs.npmjs.com/about-npm/
npm is the world’s largest software registry. Open source developers from every continent use npm to share and borrow packages, and many organizations use npm to manage private development as well.
中文释义:npm是世界上最大的软件注册中心,来自五湖四海的开源开发者利用npm来共享和借阅软件包,许多组织也通过npm来管理私有开发项目
其实,我们在安装nodejs时,已经默认安装了npm,我们可以通过npm来安装我们项目所依赖的软件包,例如,我们通过npm来安装腾讯云的SDK到我们的项目目录下
[root@zhang tencent]# npm install tencentcloud-sdk-nodejs --save[root@zhang tencent]# ls -lh total 20K drwxr-xr-x 51 root root 4.0K Apr 29 15:29 node_modules -rw-r--r-- 1 root root 13K Apr 29 15:29 package-lock.json其中安装的依赖包就就存放在node_modules目录下
[root@zhang tencent]# ls -lh node_modules/ | grep tencentc drwxr-xr-x 4 root root 4.0K Apr 29 15:29 tencentcloud-sdk-nodejs 4. 怎么实现一个nodejs网络应用?官方文档:https://nodejs.org/en/docs/guides/getting-started-guide/
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });我们在Linux中创建一个文件,将上述Demo拷贝到文件中
[root@zhang:/tmp/nodejs]$cat test.js const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });执行此nodejs脚本
[root@zhang:/tmp/nodejs]$node test.js Server running at http://127.0.0.1:3000/如果不期望阻塞当前终端,可以以后台运行的方式
[root@zhang:/tmp/nodejs]$node test.js Server running at http://127.0.0.1:3000/ ^C [root@zhang:/tmp/nodejs]$nohup node test.js & [1] 6871 [root@zhang:/tmp/nodejs]$nohup: ignoring input and appending output to ‘nohup.out’我们可以查到这个进程
[root@zhang:/tmp/nodejs]$ps -ef | grep -v "grep" | grep node root 6871 1243 0 15:46 pts/0 00:00:00 node test.js如果你想终止这个进程,可以
[root@zhang:/tmp/nodejs]$kill -9 6871现在我们访问以下这个web进程
[root@zhang:/tmp/nodejs]$curl http://zhang:3000 -w "n" Hello World其中zhang是我的主机名,我们也可以
[root@zhang:/tmp/nodejs]$curl http://127.0.0.1:3000 -w "n" Hello World那么,可能有人会问了,怎么启动一个公网可以访问的nodejs web服务呢?
当然了,上面的代码是无法实现公网访问的,公网访问的Demo如下
const http = require('http'); const port = 300; const server = http.createServer((req, res) => { res.end('hello world'); }); server.listen(port, '0.0.0.0', () => {});创建文件并执行
[root@zhang:/tmp/nodejs]$cat test-1.js const http = require('http'); const port = 300; const server = http.createServer((req, res) => { res.end('hello world'); }); server.listen(port, '0.0.0.0', () => {});[root@zhang:/tmp/nodejs]$nohup node test-1.js & [1] 11057 [root@zhang:/tmp/nodejs]$nohup: ignoring input and appending output to ‘nohup.out’通过公网访问
5. nodejs异步概念正如nodejs官方所说,其API都是异步非阻塞的;Node.js在其标准库中提供了一组异步I/O基元来防止JavaScript代码被阻塞。
When Node.js needs to perform an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
下面来演示一下nodejs的异步非阻塞
异步请求客户端Demo
var http = require('https'); var querystring = require('querystring'); var post_data = { x: "hello" } var content = querystring.stringify(post_data); var options = { hostname: 'tencentcloud.cdhwdl.com', port: 3000, path: '/', method: 'POST', headers: { 'content-type': 'application/json' } }; var req = http.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (re) { console.log(JSON.parse(re).res); }); }); req.on('error', function (e) { console.log(e.message); }); req.write(content); req.end(); console.log(2); console.log(3); console.log(4); console.log(5); console.log(6); console.log("等待5秒...")异步请求服务端Demo
const https = require('https'); const fs = require('fs'); const path = require('path'); //声明3个证书常量,因为是提供的https服务,证书需自己实现 const privateKey = fs.readFileSync(path.join(__dirname, './certificate/server.key'), 'utf8'); const certificate = fs.readFileSync(path.join(__dirname, './certificate/server.crt'), 'utf8'); const credentials = {key: privateKey, cert: certificate}; function sleep(milliSeconds) { var startTime = new Date().getTime(); while (new Date().getTime() < startTime + milliSeconds); } const httpsServer = https.createServer(credentials,function(req, res){ let body = []; req.on('data', (chunk) => { body.push(chunk); }).on('end', () => { sleep(20000); res.end(JSON.stringify({res:1})); }); }); const SSLPORT = 3000; httpsServer.listen(SSLPORT, '0.0.0.0', () => {}); 6. nodejs同步概念发起请求
[root@zhang:/tmp/nodejs]$node test-2.js 2 3 4 5 6 等待5秒...5秒后
[root@zhang:/tmp/nodejs]$node test-2.js 2 3 4 5 6 等待5秒... 1可以看到post请求并没有阻塞数字2-6的打印,在等待5秒后,获取到了异步post请求返回的1
6.nodejs异步转同步nodejs的API都是异步的,那如果项目中需要同步等待的场景,应该怎么办呢?
办法是将异步API转为同步阻塞,实现方法比较灵活,下面依次介绍几种常见的方法 第一种方法:
var http = require('https'); var querystring = require('querystring'); var post_data = { x: "hello" } var content = querystring.stringify(post_data); var options = { hostname: 'tencentcloud.cdhwdl.com', port: 3000, path: '/', method: 'POST', headers: { 'content-type': 'application/json' } }; console.log("等待5秒...") var req = http.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (re) { console.log(JSON.parse(re).res); console.log(2); console.log(3); console.log(4); console.log(5); console.log(6); }); }); req.on('error', function (e) { console.log(e.message); }); req.write(content); req.end();执行
[root@zhang:/tmp/nodejs]$node test-3.js 等待5秒... [root@zhang:/tmp/nodejs]$node test-3.js 等待5秒... 1 2 3 4 5 6可以看到等待5秒后才出现1到6, 数字2到6的打印被阻塞了,这种方式称作嵌套,不太方便代码管理
---来自腾讯云社区的---用户1529147
微信扫一扫打赏
支付宝扫一扫打赏