node js基础笔记

node

1.常用全局对象

//1.hello world
console.log('hello world')
//2.定时器
setTimeout(()=>{
  console.log('3 seconds have passed')
},3000)
//3.间隔定时
var time = 0
timer = setInterval(function(){
    time += 2
    console.log(time + 'seconds has passed')
    if(time > 10){
        clearInterval(timer)
    }
},2000)

2.模块导出的三种方式

var counter = function(arr){
    return "threre are " + arr.length + " elements in the array"
}

var adder = function(a,b){
    return `sum is ${a+b}`
}

var pi = 3.14

//1.直接导出
module.exports = counter

//2.分别导出
module.exports.counter = counter
module.exports.adder = adder
module.exports.pi = pi

//3.导出对象
module.exports = {
    counter:counter,
    adder:adder,
    pi:pi
}

//引用
var test=require('./count')

3.事件

3.1事件的使用方式

var events = require('events')

var myEmitter = new events.EventEmitter();

myEmitter.on('someEvent',function(message){
    console.log(message)
})

myEmitter.emit('someEvent','the event was emitted')

首先导入events模块

之后使用myEmitter进行new出一个对象

设定someEvent这个事件为一个函数

使用emit进行回调函数

3.2.使用场景

var events = require('events')
var util = require('util');

var Person = function(name){
    this.name=name
}

util.inherits(Person,events.EventEmitter)

var xiaoming = new Person('xiaoming')
var lili = new Person('lili')
var lucy = new Person('lucy')

var person = [xiaoming,lili,lucy]

person.forEach(function(person){
    person.on('speak',function(msg){
        console.log(person.name+' say '+msg)
    })
})

xiaoming.emit('speak','xx')
lucy.emit('speak','sdsda')
lili.emit('speak','hello')

4.文件读写

1.文件读

var fs = require('fs')
// 同步操作
var readtxt = fs.readFileSync('hellonode/txt','utf8')
fs.writeFileSync('hellonode/write',readtxt)
//异步操作
fs.readFile('hellonode/txt','utf8',(err,data)=>{
    console.log(data)
})

2.目录的创建和删除

//创建删除目录
fs.unlink('hellonode/write',function(){
    console.log('has delete');
})
fs.mkdirSync('hello')
fs.rmdirSync('hello')
fs.mkdir('hello',function(){
    console.log('sss')
})

5.输入输出流

var fs = require('fs')// 输入输出流也在fs
var myReadStream = fs.createReadStream('readme.txt')//创建读取流

var data=''
myReadStream.on('data',function(chunk){
    data+=chunk//取数据进行追加到data
})

myReadStream.on('end',function(){
    console.log(data)//结束后打印data
    console.log('finish')
})

6.简单web server

var http = require('http');//导入http
var fs = require('fs')//导入fs
var server = http.createServer(function(req,res){
    console.log('request received');
    res.writeHead(200,{
        // 'Content-Type':'text/plain'
        // 'Content-Type':'application/json'
        'Content-Type':'text/html'//写入投
    });
    // res.write('hello application')
    // var obj = {
    //     name:'steveyu',
    //     age:'21',
    //     sex:'male'
    // }
    // res.write(JSON.stringify(obj))
    // res.write(fs.readFileSync('webserver/index.html'))
    var rs = fs.createReadStream(__dirname + '/index.html')//返回文件
    rs.pipe(res)//使用管道输出
})
server.listen(3000,'127.0.0.1')//在3000端口启动
console.log('server start on localhost port')

7.web server的重构

入口app.js

var server = require('./server');
var router = require('./route')
var handler = require('./handle')

var handle = {};//建立对象映射
handle["/"] = handler.home;
handle["/index"] = handler.home;
handle["/review"] = handler.review;
handle["/json"] = handler.json;

server.startServer(router.route,handle);//开启服务

服务器server.js

var http = require('http');//http
var fs = require('fs');//fs
var url = require('url');//url

function startServer (route,handle) {
    var onRequest = function(req,res){
        var pathname = url.parse(req.url).pathname//获取路径名
        var params = url.parse(req.url,true).query;//解析params
        route(pathname,handle,res,params);//路由进行操作
    }
    var server = http.createServer(onRequest)//创建一个server
    server.listen(3000,'127.0.0.1')//监听3000端口
    console.log('server start on localhost port')
}

exports.startServer = startServer

路由route.js

function route(pathname,handle,resp,params){
    console.log('routing a request for: '+pathname)//打印路径
    if(typeof handle[pathname] === 'function'){//如果映射函数
        handle[pathname](resp,params);//进行调用
    } else {
        console.log('no handle')//否则直接打印no handle
    }
}


exports.route = route

handle.js

var fs = require('fs')

function home(res,params){
    res.writeHead(200,{'Content-Type':'text/html'});
    var rs = fs.createReadStream(__dirname + '/index.html');
    rs.pipe(res);
}

function review(res,params){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.write('<h1>review</h1>');
    res.end();
}

function json(res,params){
    res.end(JSON.stringify(params))
}


module.exports = {
    home: home,
    review: review,
    json:json
}
posted @ 2020-01-11 04:18  SteveYu  阅读(206)  评论(0编辑  收藏  举报