node.js 快速笔记
npm的常用指令
- 修改镜像源为淘宝镜像源
npm install -g cnpm --registry=https://registry.npm.taobao.org - 设置为默认源
npm config set registry http://registry.npmjs.org - 查看npm配置信息
npm config list - 查看所有包列表
npm list [-g] - 安装npm模块
npm install <Module_name> [-g]如,安装web框架 expressnpm install <Module_name - 卸载npm模块
npm uninstall <Module_name> - 升级npm模块
npm update <Module_name> - 查找npm模块
npm search <Module_name> - 创建npm模块
npm init - 查看指令帮助
npm help <command_name>
npm install 的几种类型
npm install :
会把Module包安装到node_modules目录中
不会修改package.json
之后运行npm install命令时,不会自动安装Module
npm install –save:
会把Module包安装到node_modules目录中
会在package.json的dependencies属性下添加Module
之后运行npm install命令时,会自动安装Module到node_modules目录中
之后运行npm install
–production或者注明NODE_ENV变量值为production时,会自动安装msbuild到node_modules目录中
npm install –save-dev:
会把Module包安装到node_modules目录中
会在package.json的devDependencies属性下添加Module
之后运行npm install命令时,会自动安装Module到node_modules目录中
之后运行npm install
–production或者注明NODE_ENV变量值为production时,不会自动安装Module到node_modules目录中
使用原则:
运行时需要用到的包使用–save,否则使用–save-dev (dev表开发环境)。
npm 全局安装及本地安装的却别
如npm install webpack -g与npm install webpack却别在使用时:
全局安装使用时这时:$ webpack ...
本地安装为:$ node_modules/.bin/webpack
Node.js介绍
Node.js 是一个事件驱动I/O或者事件驱动IO 服务端JavaScript环境
Node.js 是单进程单线程应用程序
Node.js 基本上所有的事件机制都是用设计模式中观察者模式实现。
Node.js REPL(交互式解释器)
Node.js REPL(Read Eval Print Loop:交互式解释器) 表示一个电脑的环境,类似 Window 系统的终端或 Unix/Linux shell
$ node>varx=0undefined>do{...x++;...console.log("x: "+x);...}while(x<5);x:1x:2REPL常用命令
ctrl + c - 退出当前终端。
tab 键 - 列出当前命令
.help - 列出使用命令
.clear - 退出多行表达式
.save filename - 保存当前的 Node REPL 会话到指定文件
.load filename - 载入当前 Node REPL 会话的文件内容。
Node.js EventEmitter
Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列
一个 net.Server 对象会在每次有新连接时触发一个事件, 一个 fs.readStream 对象会在文件被打开的时候触发一个事件。 所有这些产生事件的对象都是 events.EventEmitter 的实例。
如何使用
// 引入 events 模块varevents=require('events');// 创建 eventEmitter 对象vareventEmitter=newevents.EventEmitter();// 绑定一个匿名事件eventEmitter.on('bing_event',function(arg1,agr2){console.log('bing_event 事件被触发:'+arg1+','+agr2);});// 定义另一个事件处理方法varbing2_event=function(){console.log('bing2 事件被触发!');eventEmitter.removeAllListeners('bing_event');console.log('所有监听bing_event的都移除了');}// 绑定一个已定义的事件处理方法到 bing_event中eventEmitter.on('bing_event',bing2_event);setTimeout(function(){eventEmitter.emit('bing_event','a1','a2');},1000);varlistenerN=eventEmitter.listenerCount('bing_event');console.log('bing_event监听者数为:'+listenerN);console.log('run end!');模块系统
为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。一个文件就是一个模块,该文件可能是 JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
// Hello.jsfunctionHello(){varname;this.setName=function(thyName){name=thyName;}this.sayHello=function(){console.log('Hello,my name is '+name);}}module.exports=Hello;// index.jsvarHello=require('./Hello');hello=newHello();hello.setName('Bing');hello.sayHello();console.log('demo end.');函数
在JavaScript中,一个函数可以作为另一个函数的参数。我们可以先定义一个函数,然后传递,也可以在传递参数的地方直接定义函数。
Node.js中函数的使用与Javascript类似
functionsay(msg){console.log(msg);}functionexec(sayFun,msg){sayFun(msg);}exec(say,'hello js Function.');同样,exec中的sayFun参数也可传递匿名函数.
util实现对象继承(util.inherits)
util.inherits(constructor, superConstructor) 是一个实现对象间原型继承的函数。
varutil=require('util');// 定义父类functionBaseObj(){this.name='baseObj';this.base=1887;this.sayHello=function(){console.log('Hello This is '+this.name);};}// 给父类添加定义原型方法BaseObj.prototype.showName=function(){console.log(this.name);};// 定义子类functionSubObj(){this.name='subObj';}// 使SubObj 继承 BaseObjutil.inherits(SubObj,BaseObj);varbaseObj=newBaseObj();baseObj.showName();baseObj.sayHello();console.log(baseObj);varsubObj=newSubObj();subObj.showName();//objSub.sayHello(); //这个方法无法输出,会报错,应该sayHello不是BaseObj的原型方法,即不是通过BaseObj.prototype来定义的。console.log(subObj);注意:SubObj 仅仅继承了BaseObj 在原型中定义的函数,而构造函数内部创造的 base 属 性和 sayHello 函数都没有被 SubObj 继承。
同时,在原型中定义的属性不会被 console.log 作 为对象的属性输出。
util.inspect
util.inspect(object,[showHidden],[depth],[colors]) 是一个将任意对象转换 为字符串的方法,通常用于调试和错误输出。它至少接受一个参数 object,即要转换的对象。
showHidden 是一个可选参数,如果值为 true,将会输出更多隐藏信息。
depth 表示最大递归的层数,如果对象很复杂,你可以指定层数以控制输出信息的多 少。如果不指定depth,默认会递归2层,指定为 null 表示将不限递归层数完整遍历对象。 如果color 值为 true,输出格式将会以ANSI 颜色编码,通常用于在终端显示更漂亮 的效果。
特别要指出的是,util.inspect 并不会简单地直接把对象转换为字符串,即使该对 象定义了 toString 方法也不会调用。
Node.js 文件系统
异步的 fs.readFile() 和同步的 fs.readFileSync()
varfs=require("fs");// 异步读取fs.readFile('input.txt',function(err,data){if(err){returnconsole.error(err);}console.log("异步读取: "+data.toString());});// 同步读取vardata=fs.readFileSync('input.txt');console.log("同步读取: "+data.toString());console.log("程序执行完毕。");Node.js GET/POST请求
Get请求,如何获取表求的url信息
varhttp=require('http');varurl=require('url');varutil=require('util');http.createServer(function(req,res){// 解析 获取url参数varparams=url.parse(req.url,true).query;//true为解析为对象访问参数console.log(params);// 完成原生的urlconsole.log('req.url :'+req.url);// 获取干净的url,不带参数varpathname=url.parse(req.url).pathname;varreHtml='Your URL : '+req.url+'\n';reHtml+='URL pathname : '+pathname+'\n';reHtml+='URL Params :'+url.parse(req.url).query;res.writeHead(200,{'Content-Type':'text/plain; charset=utf-8'});res.end(reHtml);}).listen(8888);console.log('server is running ...');Post请求,如何获取body内容
POST 请求的内容全部的都在请求体中,http.ServerRequest 并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的POST请求会大大消耗服务器的资源,所以 node.js 默认是不会解析请求体的,当你需要的时候,需要手动来做。
varhttp=require('http');varquerystring=require('querystring');varpostHTML='<html><head><meta charset="utf-8"><title>Post 实现</title></head>'+'<body>'+'<form method="post">'+'网站名: <input name="name"><br>'+'网站 URL: <input name="value"><br>'+'<input type="submit">'+'</form>'+'</body></html>';http.createServer(function(req,res){varbody="";req.on('data',function(chunk){body+=chunk;});req.on('end',function(){// 解析参数body=querystring.parse(body);// 设置响应头部信息及编码res.writeHead(200,{'Content-Type':'text/html; charset=utf8'});if(body.name&&body.url){// 输出提交的数据res.write("name:"+body.name);res.write("<br>");res.write("value:"+body.url);}else{// 输出表单res.write(postHTML);}res.end();});}).listen(8888);console.log('server is running ...');