- 一。nodejs简介
Node.js 就是运行在服务端的 JavaScript。
Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。
Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。
学习网站:
API 文档 | Node.js 中文网
Node.js 教程 | 菜鸟教程
二。nodejs安装
1》安装运行环境
安装nodejs 下载地址:(Download | Node.js) 安装完成后
C:\Users\Administrator>node -v
v8.11.4
NPM的全称是(Node Package Manager),NPM是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,常见的使用场景有以下几种:
- 允许用户从NPM服务器下载别人编写的第三方包到本地使用。
- 允许用户从NPM服务器下载并安装别人编写的命令行程序到本地使用。
- 允许用户将自己编写的包或命令行程序上传到NPM服务器供别人使用。
查看npm版本号
C:\Users\Administrator>npm -v
5.6.0
已经安装了npm进行升级
npm install -g npm
由于npm安装的库和执行文件在国外 可以安装淘宝的工具cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
默认window上安装cnpm的目录是 :C:\Users\Administrator\AppData\Roaming\npm
查看cnpm的配置
C:\Users\jiaozi>cnpm config list
; cli configs
disturl = "https://npm.taobao.org/mirrors/node"
metrics-registry = "https://registry.npm.taobao.org/"
registry = "https://registry.npm.taobao.org/"
scope = ""
user-agent = "npm/6.4.0 node/v6.11.0 win32 x64"
userconfig = "C:\\Users\\jiaozi\\.cnpmrc"
; node bin location = D:\learn\node-v6.11.0-win-x64\node.exe
; cwd = C:\Users\jiaozi
; HOME = C:\Users\jiaozi
; "npm config ls -l" to show all defaults.
查看npm的配置
C:\Users\jiaozi>npm config list
; cli configs
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.4.0 node/v6.11.0 win32 x64"
; node bin location = D:\learn\node-v6.11.0-win-x64\node.exe
; cwd = C:\Users\jiaozi
; HOME = C:\Users\jiaozi
; "npm config ls -l" to show all defaults.
从以上配置可以看出 npm的搜索镜像地址是:https://registry.npmjs.org
cnpm的搜索镜像地址是:https://registry.npm.taobao.org/
如果需要将npm的镜像也修改为 淘宝的镜像地址 需要使用npm config命令
C:\Users\jiaozi>npm config
npm ERR! Usage:
npm ERR! npm config set <key> <value>
npm ERR! npm config get [<key>]
npm ERR! npm config delete <key>
npm ERR! npm config list [--json]
npm ERR! npm config edit
npm ERR! npm set <key> <value>
npm ERR! npm get [<key>]
比如将镜像地址修改(配置是键值对)
npm config set registry "https://registry.npm.taobao.org/"
npm config set disturl "https://npm.taobao.org/mirrors/node"
npm config set metrics-registry "https://registry.npm.taobao.org/"
如果删除配置 (npm config delete 键)
最后查看npm的配置
C:\Users\jiaozi>npm config list
; cli configs
scope = ""
user-agent = "npm/6.4.0 node/v6.11.0 win32 x64"
; userconfig C:\Users\jiaozi\.npmrc
disturl = "https://npm.taobao.org/mirrors/node"
metrics-registry = "https://registry.npm.taobao.org/"
registry = "https://registry.npm.taobao.org/"
测试使用npm安装redis
搜索所有npm支持的库的地址(npm)
npm常用命令(从npmjs上搜索名称):
npm install 安装模块 默认安装在当前命令行目录 -g全局安装 安装在全局目录下
npm uninstall 卸载模块
npm init 创建nodejs项目 生成 package.json文件
比如 安装redis
执行命令
C:\tttt>cnpm install redis -g
查看 C:\Users\Administrator\AppData\Roaming\npm\node_modules 下是否存在redis的库
helloworld程序实例 添加hello.js文件 添加内容
var i='hello world';
console.log(i);
执行
C:\tttt>node hello.js
hello world
命令缩写
| 参数 | 缩写 | 备注 |
|---|---|---|
| install | i | |
| uninstall | uni | cnpm 不支持这个缩写 |
| –save-dev | -D | |
| -save | -S |
简要介绍package.json文件
name:程序名称
version:版本号
description:描述信息,有助于搜索
main: 入口文件,一般都是 index.js
scripts:支持的脚本,默认是一个空的 test
keywords:关键字,有助于在人们使用 npm search 搜索时发现你的项目
author:作者信息
license:默认是 MIT
bugs:当前项目的一些错误信息,如果有的话
dependencies:在生产环境中需要用到的依赖
devDependencies:在开发、测试环境中用到的依赖
比如
"devDependencies": {
"babel-core": "^6.14.0",
}
"dependencies": {
"weex-html5": "^0.3.2",
"weex-components": "*"
}
~ ^ *代表的意思是
如果一个项目打算与别人分享,应该从 1.0.0 版本开始。以后要升级版本应该遵循以下标准:
1.补丁版本:解决了 Bug 或者一些较小的更改,增加最后一位数字,比如 1.0.1
2.小版本:增加了新特性,同时不会影响之前的版本,增加中间一位数字,比如 1.1.0
3.大版本:大改版,无法兼容之前的,增加第一位数字,比如 2.0.0
了解了提供者的版本规范后, npm 包使用者就可以针对自己的需要填写依赖包的版本规则。
作为使用者,我们可以在 package.json 文件中写明我们可以接受这个包的更新程度(假设当前依赖的是 1.0.4 版本):
如果只打算接受补丁版本的更新(也就是最后一位的改变),就可以这么写:
1.0
1.0.x
~1.0.4
如果接受小版本的更新(第二位的改变),就可以这么写:
1
1.x
^1.0.4
如果可以接受大版本的更新(自然接受小版本和补丁版本的改变),就可以这么写:
*
x
将来安装该模块 npm install 自动将依赖的包下载下来
2》nodejs管理工具安装
》》npm
npm是nodejs的包管理器,我们每次安装包的时候,使用的装包工具都是npm;
window直接安装nodejs包自带
linux下可使用yum安装
yum search npm && yum -y install npm
npm设置私服
npm config set registry https://mirrors.huaweicloud.com/repository/npm/
npm切换版本
npm install npm@7.10.0 -g
》》nrm
nrm(npm registry manager )是npm 资源管理器,允许你快速切换npm 源
使用npm安装
npm install -g nrm
查看所有默认注册npm源
C:\Users\GVT>nrm ls
npm -------- https://registry.npmjs.org/
yarn ------- https://registry.yarnpkg.com/
cnpm ------- http://r.cnpmjs.org/
taobao ----- https://registry.npm.taobao.org/
nj --------- https://registry.nodejitsu.com/
npmMirror -- https://skimdb.npmjs.com/registry/
edunpm ----- http://registry.enpmjs.org/
常用命令
C:\Users\GVT>nrm ls 查看所有源
* npm -------- https://registry.npmjs.org/
yarn ------- https://registry.yarnpkg.com/
cnpm ------- http://r.cnpmjs.org/
taobao ----- https://registry.npm.taobao.org/
nj --------- https://registry.nodejitsu.com/
npmMirror -- https://skimdb.npmjs.com/registry/
edunpm ----- http://registry.enpmjs.org/
C:\Users\GVT>nrm current 查看当前源
npm
C:\Users\GVT>nrm use taobao 使用某个源
Registry has been set to: https://registry.npm.taobao.org/
C:\Users\GVT>npm config list | grep regi 查看当前nodejs的源是否切换
metrics-registry = "https://registry.npm.taobao.org/"
registry = "https://registry.npm.taobao.org/"
C:\Users\GVT>nrm use npm
Registry has been set to: https://registry.npmjs.org/
C:\Users\GVT>npm config list | grep regi
metrics-registry = "https://registry.npmjs.org/"
registry = "https://registry.npmjs.org/"
》》npx
npm v5.2.0 引入的一条命令(npx),npx 会帮你执行依赖包里的二进制文件。引入这个命令的目的是为了提升开发者使用包内提供的命令行工具的体验。
在以往中,我们在 node 项目中要执行一个脚本,需要将它在 scripts 中声明
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"init:runtime-only": "vue init webpack vue-cms"
}
然后执行命令
npm run init:runtime-only
它其实本质还是运行名称后面对应命令: vue init webpack vue-cms
用了 npx 以后呢,你不需要在 scripts 中声明了,就可以直接敲键盘了(npx 开头,然后接你要执行的内容):
npx vue init webpack vue-cms
就算你vue命令不在全局path只是通过--save-dev安装的都可以帮你找到直接运行
npx 搜索顺序 node_modules/.bin 目录–》 系统环境变量 Path 配置 --》 远程库
npx 在本地搜索不到相关的包的时候会自动搜索远程库,然后下载安装它到一个临时目录使用之后,再删除。
案例:项目内部使用webpack
npm i webpack -D == npm install webpack --save-dev
如果需要调用只能通过:mode_modules/.bin/webpack 调用
有了 npx 之后,就可以直接使用 npx webpack来调用 webpack 了
》》cnpm
因为npm安装插件是从国外服务器下载,受网络影响大,可能出现异常,所以我们乐于分享的淘宝团队干了这事。来自官网:“这是一个完整 npmjs.org 镜像,你可以用此代替官方版本(只读,不能发布自己的包或注册用户),同步频率目前为 10分钟 一次以保证尽量与官方服务同步。”
安装:
npm install cnpm -g --registry=https://registry.npm.taobao.org
也可以直接使用nrm切换源。
》》nvm
在开发中,有时候对node的版本有要求,有时候需要切换到指定的node版本来重现问题等。遇到这种需求的时候,我们需要能够灵活的切换node版本。nvm就是为解决这个问题而产生的,他可以方便的在同一台设备上进行多个node版本之间切换
默认nvm不支持window,可安装nvm-windows版本:
下载地址:https://github.com/coreybutler/nvm-windows/releases
下载 nvm-setup.zip 直接图形界面安装,会自动管理当前已经存在的nodejs版本
C:\Users\GVT>nvm list
* 10.15.3 (Currently using 64-bit executable)
查看当前可用的版本(具体版本参考:Index of /download/release/)
C:\Users\GVT>nvm list available
| CURRENT | LTS | OLD STABLE | OLD UNSTABLE |
|--------------|--------------|--------------|--------------|
| 14.2.0 | 12.16.3 | 0.12.18 | 0.11.16 |
| 14.1.0 | 12.16.2 | 0.12.17 | 0.11.15 |
| 14.0.0 | 12.16.1 | 0.12.16 | 0.11.14 |
| 13.14.0 | 12.16.0 | 0.12.15 | 0.11.13 |
| 13.13.0 | 12.15.0 | 0.12.14 | 0.11.12 |
| 13.12.0 | 12.14.1 | 0.12.13 | 0.11.11 |
| 13.11.0 | 12.14.0 | 0.12.12 | 0.11.10 |
| 13.10.1 | 12.13.1 | 0.12.11 | 0.11.9 |
| 13.10.0 | 12.13.0 | 0.12.10 | 0.11.8 |
| 13.9.0 | 10.20.1 | 0.12.9 | 0.11.7 |
| 13.8.0 | 10.20.0 | 0.12.8 | 0.11.6 |
| 13.7.0 | 10.19.0 | 0.12.7 | 0.11.5 |
| 13.6.0 | 10.18.1 | 0.12.6 | 0.11.4 |
| 13.5.0 | 10.18.0 | 0.12.5 | 0.11.3 |
| 13.4.0 | 10.17.0 | 0.12.4 | 0.11.2 |
| 13.3.0 | 10.16.3 | 0.12.3 | 0.11.1 |
| 13.2.0 | 10.16.2 | 0.12.2 | 0.11.0 |
| 13.1.0 | 10.16.1 | 0.12.1 | 0.9.12 |
| 13.0.1 | 10.16.0 | 0.12.0 | 0.9.11 |
| 13.0.0 | 10.15.3 | 0.10.48 | 0.9.10 |
This is a 部分列表. 查看完整列表, 请访问 https://nodejs.org/download/release
常用命令
nvm install 10.15.0 //安装指定的版本的nodejs
nvm use 10.15.0 //使用指定版本的nodejs
nvm node_mirror https://npm.taobao.org/mirrors/node/
: 设置nodejs版本镜像: https://npm.taobao.org/mirrors/node/
nvm npm_mirror https://npm.taobao.org/mirrors/npm/
:设置npm淘宝镜像 https://npm.taobao.org/mirrors/npm/
其他命令:参考官网:https://github.com/coreybutler/nvm-windows
nvm arch :显示node是运行在32位还是64位。
nvm install <version> [arch] :安装node, version是特定版本也可以是最新稳定版本latest。可选参数arch指定安装32位还是64位版本,默认是系统位数。可以添加--insecure绕过远程服务器的SSL。
nvm list [available] :显示已安装的列表。可选参数available,显示可安装的所有版本。list可简化为ls。
nvm on :开启node.js版本管理。
nvm off :关闭node.js版本管理。
nvm proxy [url] :设置下载代理。不加可选参数url,显示当前代理。将url设置为none则移除代理。
nvm node_mirror [url] :设置node镜像。默认是https://nodejs.org/dist/。如果不写url,则使用默认url。设置后可至安装目录settings.txt文件查看,也可直接在该文件操作。
nvm npm_mirror [url] :设置npm镜像。https://github.com/npm/cli/archive/。如果不写url,则使用默认url。设置后可至安装目录settings.txt文件查看,也可直接在该文件操作。
nvm uninstall <version> :卸载指定版本node。
nvm use [version] [arch] :使用制定版本node。可指定32/64位。
nvm root [path] :设置存储不同版本node的目录。如果未设置,默认使用当前目录。
nvm version :显示nvm版本。version可简化为v。
nvm所有设置项都在settting.txt文件中
C:\Users\GVT>which nvm
C:\Users\GVT\AppData\Roaming\nvm\nvm.EXE
查看该目录的setting.txt可以查看到刚刚设置的私服地址:
root: C:\Users\GVT\AppData\Roaming\nvm
arch: 64
proxy: none
originalpath: .
originalversion:
node_mirror: https://npm.taobao.org/mirrors/node/
npm_mirror: https://npm.taobao.org/mirrors/npm/
》》yarn
facebook发布的新一代包管理工具,旨在解决以往使用npm作为包管理会遇到的一些问题。从其官方介绍可以看到其重点强调的3个点:快、可靠、安全。
yarn拥有以下6个特性:
- 离线模式: 一次安装,永久使用,无需下载
- 依赖确定性:安装依赖锁定,保证一致性.
- 更好的网络性能:下载包,优化网络请求,最大限度提高网络利用率
- 多注册来源处理:不管依赖包被不同的库间接关联引用多少次,安装这个包时,只会从一个注册来源去装(npm/bower), 防止出现混乱不一致。
- 网络弹性处理: 安装依赖时,不会因为某个单次网络请求的失败导致整个安装挂掉。当请求失败时会进行自动重试。
- 扁平模式: 当关联依赖中包括对某个软件包的重复引用,在实际安装时将尽量避免重复的创建
Yarn和npm命令对比
| npm | yarn |
|---|---|
| npm install | yarn |
| npm install react --save | yarn add react |
| npm uninstall react --save | yarn remove react |
| npm install react --save-dev | yarn add react --dev |
| npm update --save | yarn upgrade |
| npm install xxx --global | yarn global add xxx |
| npm init | yarn init |
| npm run | yarn run |
| npm cache clean | yarn cache clean |
| npm login | yarn login (logout 同理) |
| npm publish | yarn publish |
3》安装ide工具
目前比较流行的几款nodejs开发工具 ,webstorm(收费),visualstudiocode(免费) 我这里主要介绍vscode 因为开源有
微软支持 并且支持typescript
下载地址:Visual Studio Code - Code Editing. Redefined
安装后 打开之前的目录 File-Open Folder 选择目录(ctrl+f5 运行 f5调试 f10调试到下一行 )
要运行确保 环境变量下有node.exe文件 node -v能执行即可
vscode提供了强大了提示功能 比如require了一个模块js 直接能提示他的方法和语法
提供 模块点击查看功能 比如
require("fs"); 点击fs可以链接到模块源代码
三。nodejs常用语法
学习过javascript 基本nodejs语法是一模一样的 只是nodejs强大的require模块功能, 同时nodejs支持es6的语法 具体参考
比如简化的匿名函数
var xfun=(x)=>x*2; //等价于 function(x){return x*2}
console.log(xfun(10));
/**
* 等价于
* function(x,y){}
*/
var yfun=(x,y)=>{
return x+y;
}
console.log(yfun(10,20));
比如类的定义参考ES6 入门教程
class UserInfo {
constructor(userName){
this.userName=userName;
}
print(){
console.log(this.userName);
}
}
Object.assign(UserInfo.prototype,{
toString1(){
console.log("toString:"+this.userName);
}
})
var userInfo=new UserInfo("zs");
userInfo.print();
userInfo.toString1();
1。 文件操作api (fs模块)
具体参考 Node.js 文件系统 | 菜鸟教程
简单操作下读和写
fs.readFile("c:/a.txt",function(err,data){
console.log(data.toString());
//数据的总行数
console.log("长度是:"+data.toString().split("\n").length);
})
//fs.mkdir("c:/hello");
fs.writeFile("c:/a.txt","hello",{flag:"a"}); //flag表示读r写w追加a
//流操作
var readerStream = fs.createReadStream('c:/a.txt');
var dd='';
readerStream.on("data",d=>{
dd+=d;
console.log("读取到一行:"+d);
});
readerStream.on('end',function(){
console.log("所有的数据"+dd);
});
//将流的数据管道接通另外一个输出流
var writerStream = fs.createWriteStream('c:/a_1.txt');
readerStream.pipe(writerStream);
writerStream.end;
2。 事件循环 (evens模块)
具体参考 Node.js 事件循环 | 菜鸟教程
简单演示:
var e=require("events");
var evc=new e.EventEmitter();
//绑定一个事件
evc.on("init",function(p){
console.log("初始化"+p[0]);
})
//触发事件
evc.emit("init",["hello"]);
3。缓冲区
具体参考Node.js Buffer(缓冲区) | 菜鸟教程
简单演示:
var buff=Buffer.alloc(100);
buff.write("hello");
console.log(buff.toString("utf8"));
console.log(buff.toString("base64"));
4。自定义模块
用户可以自定义js模块 然后导出 其他js就可以引用 比如添加一个fun.js导出一个hello方法
参考 Node.js 模块系统 | 菜鸟教程
function hello(){
console.log("helloworld");
}
function print(x){
console.log(x);
}
exports.hello=hello;
其他js调用
var fun=require("./fun");
fun.hello();
fun.print() //报错 没有导出
5。面向对象
class UserInfo {
constructor(userName){
this.userName=userName;
}
print(){
console.log(this.userName);
}
}
UserInfo.prototype.eat=()=>{
console.log(this.userName+"正在吃饭");
}
Object.assign(UserInfo.prototype,{
toString1(){
console.log("toString:"+this.userName);
}
})
var userInfo=new UserInfo("zs");
userInfo.print();
userInfo.toString1();
userInfo.eat();
//util模块的用法
//不支持接口 typescript才支持
class Person{
constructor(name){
this.name=name;
}
walk(){
console.log(this.name+"走路");
}
}
class Chinese extends Person{
constructor(name){
super(name);
}
}
const zs=new Chinese("zs");
zs.walk();
6。网络相关
url模块(统一资源定位符)
//url类的用法
var url=require("url");
var urlp=url.parse("http://www.baidu.com/abc?id=1&name=zs",true);//第二个参数为true query会被解析成json 否则就是连接字符串
console.log(urlp);
console.log(urlp.query);//id=1&name=zs 或者 {id:1,name:'zs'}
console.log(urlp.path);///abc?id=1&name=zs
console.log(urlp.query.id+"--"+urlp.query.name);
http模块
//http模块的用法
var http=require("http");
http.createServer((req,res)=>{
console.log(req.url);
//解析url后获取查询字符串 参数 id=1
var queryParam=url.parse(req.url).query;
console.log(queryParam.name);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<font color=red>hello</font>");
res.end();
}).listen(8809);
上例 模拟一个简单的http服务器,浏览器访问 http://localhost:8809 即可输出
发送请求
//参考http://nodejs.cn/api/http.html#http_http_request_options_callback
var http=require("http");
var querystring=require("querystring");
const postData = querystring.stringify({
'wd' : 'Hello!'
});
const req=http.request({
hostname: 'www.baidu.com',
port: 80,
path: '/s',
method: 'get',
},(res)=>{
console.log(`状态码: ${res.statusCode}`);
console.log(`响应头: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`响应主体: ${chunk}`);
});
})
req.write(postData);//注意 因为百度只能get请求 如果要发送这个数据 应该用post请求 这里是模拟
//get请求的参数应该放在 path上
req.end();
tcp模块(net)
建议tcp服务器和tcp客户端实例
tcp服务器代码
//创建一个tcp
var net=require("net");
//创建一个服务器坚挺8778端口
const s=net.createServer((c)=>{
console.log('有客户端连接 connected');
c.on("data",(d)=>{
console.log("接受到数据"+d.toString());
c.end();
});
c.write("hello\n");
c.pipe(c);
}).listen(8778);
tcp客户端代码
var net=require("net");
const client=net.connect({port:8778},function(){
client.write("helloserver\n");
});
client.on("data",function(d){
console.log(d.toString());
client.end();
});
本文详细介绍了Node.js的基础知识,包括其概念、安装步骤、常用语法及模块系统。涵盖Node.js环境搭建、npm包管理器的使用技巧、IDE工具推荐、文件操作、事件循环、缓冲区应用、自定义模块创建、面向对象编程、URL与HTTP模块解析及TCP网络编程实例。
8576

被折叠的 条评论
为什么被折叠?



