美文网首页
nodejs笔记

nodejs笔记

作者: 林思念 | 来源:发表于2024-01-10 13:45 被阅读0次

一、Api模块

1、内置模块

  • os 操作系统
  • path 路径
  • fs 文件读写
const fs = require('fs')
fs.stat('hello.js', (err, stats) => {
  if(error){
    console.log(err)
  } else {
    console.log(stats)
    console.log('文件:' + stats.isFile())
    console.log('目录:' + stats.isDirectory())
  }
})
fs.mkdir('log', (err) => {
  if(err){
    console.log(err)
  } else {
    console.log('成功创建!')
  }
})
fs.writeFile('log/hellos.js', 'console.log("writeFile")',(err) =>{
  if(err){
    console.log(err)
  } else {
    console.log('写入成功')
  }
})
// 追加内容
fs.appendFile('log/hellos.js', 'console.log("writeFile")',(err) =>{
  if(err){
    console.log(err)
  } else {
    console.log('写入成功')
  }
})
fs.readFile('log/hellos.js', 'utf8', (err, data) =>{
  if(err){
    console.log(err)
  } else {
    console.log(data)
  }
})
// 读取文件列表
fs.readdir('log', (err, files) => {
  if(err){
    console.log(err)
  } else {
    console.log(files)
  }
})
// [ 'hello.js' ]
fs.rename('log', 'logs', (err) =>{
  if(err){
    console.log(err)
  } else {
    console.log('修改名字成功!')
  }
})
// 删除目录
fs.readdirSync('logs').map(file =>{
  fs.unlink(`logs/${file}`, (err) =>{
    if(err){
      console.log(err)  
    } else {
      console.log('删除文件: logs/' + file + '成功!')
    }
  })
})
fs.rmdir('logs', (err) =>{
  if(err){
    console.log(err)
  } else {
    console.log('删除成功!')
  }
})
// 删除文件
fs.unlink('hello.js', (err) =>{
  if(err){
    console.log(err)
  } else {
    console.log('成功删除文件!')
  }
})
  • stream (大文件读写)
const fs = require('fs')
const fileReadStream = fs.createReadStream('data.json')
const fileWriteStream = fs.createWriteStream('data-1.json')
let count = 0
fileReadStream.on('once', (chunk) =>{
  console.log(chunk.toString())
})
fileReadStream.on('data', (chunk) =>{
  console.log(`第${++count}次接收到${chunk.length}`)
  fileWriteStream.write(chunk)
})
fileReadStream.on('end', (chunk) =>{
  console.log('结束!')
})
// 管道 pipe
const fs = require('fs')
const zlib = require('zlib') // gzip压缩模块

const fileReadStream = fs.createReadStream('data.json')
const fileWriteStream = fs.createWriteStream('data.json.gz')

fileWriteStream.on('pipe', (source) => {
  console.log(source)
})

fileReadStream
  .pipe(zlib.createGzip()) // 增加gzip压缩过程
  .pipe(fileWriteStream)  // 读取流写入
  • require 导入模块
  • url url解析
url.parse('https://www.baidu.com/')  // 解析url,返回url对象
url.format() // 逆向parse

// resolve
url.resolve('/one/two/three', 'four');         // '/one/two/four'
url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
  • querystring
// 正反序列化
querystring.parse("{name: 'sgr’, age: '26'}")
querystring.stringify({name: 'sgr’, age: '26'})
// 正反编码
querystring.escape('北京')
querystring.unescape('%E5%8C%97%E4%BA%AC')
  • htttp
const http = require('http')
const https = require('https')
const url = 'https://www.lagou.com/wn/'

https.get(url, function(res){
  let html = ''
  res.on('data', function(data){
    html += data
  })
  res.on('end', function(){
    console.log(html)
  })
  res.on('error', function(err){
    console.log(err)
  })
})
  • https
// get请求
const https = require('https')
const options = {
  hostname: 'api.douban.com',
  port: 443,
  path: '/v2/movie/top250',
  method: 'GET'
}; 
let responseData = ''
const req = https.request(options, res => {
  res.setEncoding('utf8')
  res.on('data', function(html){
    console.log('状态码:', res.statusCode);
    responseData += html
  })
  res.on('end', function(){
    console.log(JSON.parse(responseData))
  })
  res.on('error', function(error){
    console.log(error);
  })
})
request.on('error', function(){
})
request.end()
const https = require('https')
const querystring = require('querystring')

const postData = querystring.stringify({
  title: 'css 外部文件如何引入',
  content: '<p>css 外部文件如何引入</p>',
  courseId: '227',
  lessonId: '1753'
})
var options = {
  hostname: 'www.baidu.com',
  port: 80,
  methods: 'POST',
  path: '/ajax/create/course/question',
  header: {
    Accept: '*'
  }
}
var responseData = ''
const request = https.request(options, (response) =>{
  response.setEncoding('utf8')
  response.on('data', res=> {
    console.log(res)
  })

  response.on('end', res=> {
    console.log('end')
  })
})
request .on('error', function(){
  console.log(error)
})
request .end()
  • events
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {    //  用于注册监听器
  console.log('触发了一个事件!');
});
myEmitter.emit('event');          //  用于触发事件

2、三方模块

  • nodemon
    热更新模块,更改代码后执行js
  • cheerio
    node端的jquery
npm install cheerio

const cheerio = require('cheerio')

res.on('end', function(){
  // console.log(html)
  filterMenu(html)
})

function filterMenu(html){
    const $ = cheerio.load(html)
    let menu = $('.menu_box')
    let menuData = []
    menu.each(function(index, value){
        const title = $(value).find('h2').text()
        const lists = $(value).find('a')
        const menuList = []
        lists.each(function(index, value){
            menuList.push($(value).text())
        })
        console.log(title, menuList)
    })
}
  • request
request({
  url: 'https://api.douban.com/v2/movie/top250',
  json: true
}, (err, response, bod) =>{
  console.log(JSON.stringify(body, null, 2))
  console.log(err, response, body)
})
// 串行 无关联 数组
const async = require('async')

console.time('test')
async.series([
    function (callback) {
        setTimeout(() => {
            callback(null, 'one')
        }, 2000)
    },
    function (callback) {
        setTimeout(() => {
            callback(null, 'two')
        }, 5000)
    }
], function (err, result) {
    console.log(err, result)
    console.timeEnd('test') // test: 7017ms
})
// 串行 无关联 对象
const async = require('async')

console.time('test')
async.series({
    one: function (callback) {
        setTimeout(() => {
            callback(null, '1')
        }, 1000)
    },
    two: function (callback) {
        setTimeout(() => {
            callback(null, '2')
        }, 3000)
    }
}, function (err, result) {
    console.log(err, result)
    console.timeEnd('test')
})
// 并行 无关联 数组
const async = require('async')

console.time('test')
async.parallel([
    function (callback) {
        setTimeout(() => {
            callback(null, 'one')
        }, 2000)
    },
    function (callback) {
        setTimeout(() => {
            callback(null, 'two')
        }, 5000)
    }
], function (err, result) {
    console.log(err, result)
    console.timeEnd('test') // test: 7017ms
})
// 串行 有关联
const async = require('async')

console.time('test')
async.waterfall([
    function(callback){
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback){
        console.log('arg1 => ' + arg1);
        console.log('arg2 => ' + arg2);
        callback(null, 'three');
    },
    function(arg3, callback){
        console.log('arg3 => ' + arg3);
        callback(null, 'done');
    }
], function (err, result) {
   console.log('err => ' + err);
   console.log('result => ' + result);
})

3、自定义模块

const helle = () => {
  console.log('hello~')
}
module.exports.hello = hello

const greeting = require('./src/greeting.js')
greeting.hello()

二、Node创建后端路由

  • 创建服务器
const http = require('http')
const url = require('url')
const router = require('./router')

http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  if(req.url !== '/favicon.ico'){
    var pathname = url.parse(req.url).pathname
    console.log(pathname)
    router[pathname](req, res)
  }
  res.end()
}).listen(8000)
console.log('Server running at http://localhost:8000/')
  • supervisor // 热更新服务器文件修改
npm install supervisor -g
supervisor server.js
  • router.js
const file = require('./file')
module.exports = {
  home: function(req, res){
    res.write('首页')
  },
  login: function(req, res){
    res.write('登录')
  },
  image: function(req, res){
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    file.readImg('./images/1.jpeg', res)
  },
  register: function(req, res){
    res.write('注册')
  }
}
  • file.js
var fs = require('fs')

module.exports = {
  readImg: function(file, res){
    fs.readFile(file, 'binary', (err, data) => {
      if(err)throw err;
      res.writeHead(200, {'Content-Type': 'image/jpeg'})
      res.write(data, 'binary') 
      res.end()
    })
  }
}
  • 读取图片
var http = require('http')
const url = require('url')
const router = require('./js/router')
const file = require('./js/file')

http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  // res.writeHead(200, {'Content-Type': 'image/jpeg'})
  if(req.url !== '/favicon.ico'){
    let pathname = url.parse(req.url).pathname.slice(1)
    console.log('pathname', pathname)
    try{
      router[pathname](req, res)
    }catch(e){
      router['home'](req, res)
    }
  }
}).listen(8000)
  • 读取文件和页面
    router.js
const file = require('./file')
module.exports = {
  home: function(req, res){
    file.readFile('./views/home.html', res, req)
  },
  login: function(req, res){
    file.readFile('./views/login.html', res, req)
  },
  image: function(req, res){
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    file.readImg('./images/1.jpeg', res)
  },
  register: function(req, res){
    file.readFile('./views/register.html', res, req)
  }
}

file.js

var fs = require('fs')

module.exports = {
  readFile: function(file, res, req){
    console.log(5, file)
    fs.readFile(file, 'utf-8', function(err, data){
      if(err) throw err;
      res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
      res.write(data)
      res.end()
    })
  },
  readImg: function(file, res){
    fs.readFile(file, 'binary', (err, data) => {
      if(err)throw err;
      res.writeHead(200, {'Content-Type': 'image/jpeg'})
      res.write(data, 'binary') 
      res.end()
    })
  }
}

server.js

var http = require('http')
const url = require('url')
const router = require('./js/router')
const file = require('./js/file')

http.createServer(function(req, res){
  if(req.url !== '/favicon.ico'){
    let pathname = url.parse(req.url).pathname.slice(1)
    console.log('pathname', pathname)
    try{
      router[pathname](req, res)
    }catch(e){
      router['home'](req, res)
    }
  }
}).listen(8000)
  • 表单提交
    router.js
const file = require('./file')

module.exports = {
  home: function (req, res) {
    file.readFile('./views/home.html', res, req)
  },
  login: function (req, res) {
    let post = ''
    req.on('data', function(chunk){
      console.log(chunk)
      post += chunk
    })
    req.on('end', function(){
      file.postReadFile('./views/login.html', res, req, post)
    })
  },
  image: function (req, res) {
    res.writeHead(200, { 'Content-Type': 'image/jpeg' })
    file.readImg('./images/1.jpeg', res)
  },
  register: function (req, res) {
    file.readFile('./views/register.html', res, req)
  }
}

login.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    登录
    <div>Email: {email}, 密码:{password}</div>
    <form action="./login" method="post">
        <label for="email">
            E-mail: <input type="text" name="email" value="" />
        </label>

        <label for="password">
            密码: <input type="password" autocomplete name="password" value="" />
        </label>

        <label for="submit">
            <input type="submit" value="提交" />
        </label>
    </form>
</body>

</html>

file.js

var fs = require('fs')
var querystring = require('querystring')

module.exports = {
  postReadFile: function (file, res, req, post) {
    var urlObject = querystring.parse(post)
    var array = ['email', 'password']
    var reg;

    fs.readFile(file, 'utf-8', function (err, data) {
      console.log('data', data)
      if (err) throw err;
      res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })

      for (let i = 0; i < array.length; i++) {
        reg = new RegExp('{' + array[i] + '}', 'gi')
        data = data.replace(reg, urlObject[array[i]])
      }
      console.log('data', data)
      res.write(data)
      res.end()
    })
  } 
}

三、简易聊天功能

  • socket版本
    socketClient.js
var net = require('net')
var port = 9000
var host = '127.0.0.1'

var client = new net.Socket()
client.setEncoding = 'UTF-8'

client.connect(port, host, function(){
    client.write('您好')
})

client.on('data', function(data){
    console.log('服务端传来:' + data);
    say()
})

client.on('error', function(err){
    console.log('err:', err)
})

client.on('close', function(){
    console.log('connection closed')
})

const readline = require('readline')
const r1 = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

function say(){
    r1.question('请输入:', inputStr => {
        if(inputStr != 'bye'){
            client.write(inputStr + '\n')
        } else {
            client.distory()
        }
    })
}

socketServer.js

var net = require('net')

var chatServer = net.createServer(),
    clientMap = new Object()

var i = 0 // 连接名称的流水号

chatServer.on('connection', function(client){
    console.log('客户端有人链接')
    client.name = ++i
    clientMap[client.name] = client

    // 对客户端发送消息的监听
    client.on('data', function(data){
        console.log('客户端传来:' + data)
        broadcast(data, client)
    })

    client.on('error', function(e){
        console.log('client error:' + e)
        client.end()
    })

    client.on('close', function(data){
        delete clientMap[client.name]
        console.log(client.name + "下线")
        broadcast(client.name + '下线了', client)
    })
})

// 消息广播
function broadcast(message, client){
    for(var key in clientMap){
        clientMap[key].write(client.name + 'say: ' + message + '\n')
    }
}
chatServer.listen(9000)
  • ws版本
npm install ws

ws.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>WebSocket</h1>
    <div id="chatroom" style="width:400px;height:300px;overflow:auto;border:1px solid blue;"></div>
    <input type="text" name="sayinput" id="sayinput" value="">
    <input type="button" name="send" id="sendbutton" value="发送">
    <script src="WsClient.js" charset="utf-8"></script>
    <script type="text/javascript">
        function send() {
            ws.send(sayinput.value)
            sayinput.value = ''
        }

        document.onkeyup = function (event) {
            if (event.keycode === 13) {
                send()
            }
        }

        sendbutton.onclick = function(){
            send()
        }
    </script>
</body>

</html>

WsServer.js

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ port: 9000 })


var clientMap = new Object()
var i = 0

wss.on('connection', function (ws) {
    console.log(ws + '上线')
    ws.name = ++i
    clientMap[ws.name] = ws
    ws.on('message', function (message) {
        broadcast(message, ws)
    })
    ws.on('close', function () {
        // global.gc() // 调用内存回收 
        console.log('回收')
    })
})

function broadcast(msg, ws) {
    for (var key in clientMap) {
        clientMap[key].send(ws.name + '说:' + msg)
    }
}

WsClient.js

var ws = new WebSocket('ws://127.0.0.1:9000')

ws.onopen = function () {
    ws.send()
}

ws.onmessage = function (event) {
    var chatroom = document.querySelector('#chatroom')
    chatroom.innerHTML += '<br/>' + event.data
}

ws.onclose = function () {
    alert('closed')
}

ws.onerror = function (err) {
    alert('Error:' + err)
}
  • socket.io版本
npm install express socket.io

相关文章

  • 2018-08-21nodejs

    Nodejs学习笔记 一、 NodeJs介绍 什么是NodeJS,在应用程开发中起什么作用? Nodejs是一个应...

  • 57/666 HJDS npm read | is-sorted

    这是666计划的57篇笔记 nodejs sort demo.js: index.js: nodejs array...

  • 什么是 Node

    NodeJS笔记 什么是 Node NodeJS 是一个构建于Chrome V8 引擎之上的一个JavaScri...

  • nodejs 学习笔记(1)koa2 koa-generator

    koa2是nondejs的开发框架,最近学习nodejs,这里记记笔记 首先安装好nodejs 安装koa2,全局...

  • nodejs笔记

    nodejs教程 :http://www.runoob.com/nodejs/nodejs-tutorial.ht...

  • nodejs笔记

    nodejs常用知识点 nodejs中require方法的过程 在module.js中会先调用_load方法,当该...

  • NodeJS笔记

    函数内部单线程、异步执行 Nodejs是单线程,但是异步,为的是提高执行效率,因此如果一个函数中有回调耗时函数,会...

  • nodejs笔记

    1,nodejs启动 2,url 3,querystring 注1 : 锚点

  • nodejs笔记

    菜鸟教程 简介 简单的说 Node.js 就是运行在服务端的 JavaScript。Node.js 是一个基于Ch...

  • Nodejs笔记

    Node基本 node的最大特性莫过于基于事件驱动的非阻塞I/O模型。 node通过事件驱动的方式处理请求,无须为...

网友评论

      本文标题:nodejs笔记

      本文链接:https://www.haomeiwen.com/subject/mtvnndtx.html