Node.js基础(一)

198 阅读3分钟

Node.js的概念

Node.js 是一个基于Chrome V8引擎的JavaScript运行环境

  • 服务器端的js有什么能力

Node.js的功能

事件驱动/非阻塞I/O模型

  • 异步的输入输出,比如:文件操作、数据库操作等

Node.js的运行方式

使用Node.js编译器(node)
使用命令行(node 文件路径)

Node.js文件的监听

监听:node 文件名
实时监听:nodemon 文件名

Node.js版本

偶数版为稳定版(0.6.x ,0.8.x ,0.10.x)
奇数版为非稳定版(0.7.x ,0.9.x ,0.11.x)
最新版本 Current / 长期稳定版本 LTS

Node.js模块化

Node.js采用了Common.js模块化
应用

  • 内置模块 -> 可以直接使用
   const fs=require('fs');
   const data=fs.readFileSync('../老彭.txt','utf8');
   console.log('结果:',data)
  • 第三方模块 -> Node.js没有的 类似于插件
const request=require('request');
request('https://m.lagou.com/listmore.json',function(error,response,body){
    console.log('error:',error);
    console.log('statusCode',response && response.statusCode);
    console.log('body:',body);
});
//request:http调用最简单的方法,支持https
  • 自定义模块
自定义模块的定义
const people={
    name:'zhangsan',
    age:18
}
//暴露模块
module.exports=people;
自定义模块的使用
//引用模块
const people=require('./3-自定义模块定义.js');
console.log('People.name',people.name);
  • 自定义模块上传实现步骤

    • 1.创建文件夹,注意命名不要冲突
    • 2.创建package.json文件
      • npm init/npm init -y
    • 3.创建index.js,里面封装一个任意功能
    • 4.创建npm.js账号
      • 发送一个邮箱链接激活
    • 5.保证当前的源是npm源
      • nrm ls
      • nrm use npm
    • 6.登陆账号
      • npm adduser
    • 7.上传
      • npm publish
  • 自定义模块的上传/下载使用

自定义模块的上传
//在这里封装一个功能-->创建一个服务器
const http=require('http');
const PORT=3000;
const HOST='localhost';
const createServer=()=>{
    http.createServer((request,response)=>{
    //发送信息给前端
    response.write('Hello');
    response.end()
}).listen(PORT,HOST,()=>{
    //打印出服务器的运行地址
    console.log(`服务器运行在:http://${HOST:PORT}`)
}
//暴露模块
module.exports=createServer;
自定义模块的下载使用
const createServer=require('xige_1911');
createServer();

JSON.stringify/JSON.parse

JSON.stringify:对象转字符串 JSON.parse:字符串转对象

深拷贝
const state = {
  str: 'hello',
  obj: {
    x: 1,
    y: 2
  }
}
const newState=JSON.parse(JSON.stringify(state));
newState.str='byebye';
console.log('state',state);
console.log('newState',newState);

querystring内置模块

使用场景

  • 用于处理url上的查找字符串
    • querystring.parse (string->object)
    • querystring.stringify (object->string)
    • querystring.escape (中文转码)
    • querystring.unescape (中文解码)
    const qs=require('querystring');
    const url=require('url');
    const str = 'https://detail.tmall.com/item.htm?spm=a230r.1.14.6.7a344d82XrCvx0&id=604098442154&cm_id=140105335569ed55e27b&abbucket=2';
    const newObj = qs.parse(url.parse( str ).query);
    console.log(newObj);
    

url:用于URL解析

  • url.parse():将url字符串转化成对象
  • query属性:'?'后面的字符串,并且解析字符串(url.parse中一个属性)

path:路径

使用场景

  • 用于处理绝对路径/磁盘路径
const path = require('path');
console.log("西阁: path", path);
const pathUrl = path.resolve( __dirname, 'aa');
console.log("西阁: pathUrl", pathUrl);

HTTP模块

  • 概念:
    • Node.js 中的 HTTP 接口旨在支持传统上难以使用的协议的许多特性。 特别是,大块的、可能块编码的消息。 接口永远不会缓冲整个请求或响应,用户能够流式传输数据。
  • http.get()指向后台发送请求。不需要使用end()发送,可以自行发送
  • http.request()用于向http服务器发送请求。需要end()方法发送
  • http.response()响应请求。

events:事件

  • 概念:
    • 多数 Node.js 核心 API 构建于惯用的异步事件驱动架构,其中某些类型的对象(又称触发器,Emitter)会触发命名事件来调用函数(又称监听器,Listener)。
    • 所有能触发事件的对象都是 EventEmitter 类的实例。
    • 这些对象有一个eventEmitter.on() 函数,用于将一个或多个函数绑定到命名事件上。
    定义事件-->发布
    const archetype=events.EventEmitter.prototype;
    archetype.on('handler',(val)=>{
        console.log('事件触发了',val);
     });
     触发事件-->订阅
     archetype.emit('handler',100);
     
    

readline:逐行读取

  • 提供了一个接口。用于一次一行的读取可读流。
const readline=require('readline');
//readline.createInterface在服务器端创建了一个可以输入输出的接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.question('你如何看待 Node.js 中文网?', (answer) => {
  if(answer=='88'){
      rl.close();
  }else{}

});