Node.js常用模块

前端模块化

  • AMD ( require.js )
  • CMD ( sea.js )
  • Common.js ( module.export require )
  • es6 模块化 ( export import )

Node.js模块分为内置模块、第三方模块(插件)、自定义模块

内置模块
  • 使用步骤:
    引用模块
    var url = require ( 'url' )
    再使用模块上的方法
  • url模块 常用API
	url.parse(urlString)      String-->Object
	url.format(urlObj)         Object-->String
	url.resolve(  )	拼接
	eg: var str = ' http://localhost:8000/home/a '
	console.log( url.resolve (str,' ./b ' ) )
	// http://localhost:8000/home/b
  • path模块(磁盘模块)
    path.join 将一个目录的名称拼接到一个磁盘路径上
    path.resolve 将一个目录的名称拼接到一个磁盘路径上
    __dirname :当前文件的磁盘路径
    fs模块 操作文件或者目录
  1. 文件
	var fs = require('fs')
   	// 文件的操作
    // 增(创建)
		fs.writeFile('./dist/1.txt', 'hello yyb', function(error) {
    		if (error) throw error
		})	

	// 改

		fs.appendFile('./dist/1.txt', '\nhello 千锋~~~', 'utf8', function(error) {
    		if (error) throw error
   			 console.log('文件修改成功')
		})

	// 查
		fs.readFile('./dist/1.txt', 'utf8', function(error, data) {
   			 if (error) throw error
        	// console.log( data.toString() ) // 二进制数据
    		console.log(data)
    		console.log('文件读成功了')
		})
		
	// 删

		fs.unlink('./dist/1.txt', function(error) {
    		if (error) throw error
   			 console.log('文件删除成功')
		})
  1. 目录
	var fs = require('fs')

// 目录-增

fs.mkdir('./dist', function(error) {
    if (error) throw error
    console.log('目录创建成功')
})

// 目录-改
fs.rename('./dist', './fs_dist', function(error) {
    if (error) throw error
    console.log(' 目录名称修改成功 ')
})

// 目录-查
for (var i = 0; i < 10; i++) {
    fs.writeFile(`./fs_dist/${i}.txt`, i, function(err) {
        console.log(`第${i}个文件创建成功`)
    })
}

fs.readdir('./fs_dist', 'utf-8', function(error, data) {
    if (error) throw error
        //console.log( data  ) // 以文件名为元素构成的数组
    for (var i = 0; i < data.length; i++) {
        fs.readFile(`./fs_dist/${data[i]}`, 'utf8', function(error, content) {
            if (error) throw error
            console.log(content)
        })
    }
})

// 目录-删

fs.rmdir(path, callback) //这个方法只能删除空目录

fs.rmdir('./fs_dist', function(error) {

    if (error) throw error

    console.log('目录删除成功')

})

fs.readdir('./fs_dist', 'utf-8', function(error, data) {
    if (error) throw error
        //console.log( data  ) // 以文件名为元素构成的数组
    for (var i = 0; i < data.length; i++) {
        fs.unlink(`./fs_dist/${data[i]}`, function(error) {
            if (error) throw error
        })
    }
})


fs.rmdir('./fs_dist', function(error) {
    if (error) throw error
})
  • http 创建静态服务器
var http = require ( 'http' )
http.createServer ( function ( request, response ) {
response.write ()
response.end ()
} ).listen (	8000, 'localhost', function () {
console.log ( `服务器运行在:http://localhost:8000` )
} )
http.get()应用:爬虫

爬虫的概念:
使用数据请求一段内容,然后将这段内容做数据清洗,最后在通过后端服务器发送到前台页面

1. 数据请求, 获得数据 
2. 数据清洗 ( 工具  cheerio ) 
3. 安装 cheerio   `$ cnpm i cheerio -S`
4. 使用cheerio
5. 发送给前台

请求的网址: http://jx.1000phone.net/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiY2dn

var http = require( 'http' )
var cheerio = require( 'cheerio' )


// http.get(url/options,callback)

const options = {
  hostname: 'jx.1000phone.net',
  port: 80,
  path: '/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiY2dn',
  method: 'get',
  headers: {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cache-Control': 'no-cache',
    'Cookie': 'PHPSESSID=ST-46480-wNTDM48QXeWJfh--WJ-Oupg44Oo-izm5ejd5j1npj2pjc7i3v4z',
    'Host': 'jx.1000phone.net',
    'Pragma': 'no-cache',
    'Proxy-Connection': 'keep-alive',
    'Referer': 'http://jx.1000phone.net/teacher.php/Class/index',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
};


// 创建静态服务器

http.createServer( function ( request, response ) {

  response.writeHead( 200 , {
    'Content-type': 'text/html;charset=utf8'
  })

  var req = http.get( options,function( res ) {
    res.setEncoding('utf8');
    let rawData = '';
    res.on('data', (chunk) => { rawData += chunk; });
    res.on('end', () => {
      try {
        var $ = cheerio.load( rawData )
  
        $('td.student a').each( function( index,ele ) {
         response.write( `<h3>${$( this ).text().toString()}</h3>` )
        })

        response.end()
  
      } catch (e) {
        console.error(e.message);
      }
    })
  
  }).on('error', (e) => { // get的报错
    console.error(`problem with request: ${e.message}`);
  })
  
  req.end()

}).listen(8000,'localhost',function () {
  console.log( `服务器运行在: http://localhost:8000` )
})

第三方模块

  • querystring
    核心的方法:

        1. parse :      将String -- > Object
        	 parse( str , arg1 , arg2)
    	 	 str: 你要处理的字符
    		 arg1: 分隔字符
    		 arg2: 
     		 将 = 转化为 : , (这句话前提是 & 符号是提前被转化的)
    
        2. stringify : 将Object  -> String
    
        3. escape:     将 中文字符 编码
    
        4. unescape : 将中文字符解码
    
    
    
  • stream
    stream 流: 减少内存消耗, 增加效率
    pipe:管道流
    举例:压缩包的创建

    	var fs = require( 'fs' )
    
    	var  zlib = require('zlib')  // 创建压缩包
    
    	var readeStream = fs.createReadStream( './dist/1.txt' )
    
    	var writeStream = fs.createWriteStream( './dist/1.txt.gz' )
    
    	var gzip = zlib.createGzip() // 空压缩包
    
    	readeStream
    		 .pipe( gzip )
    		 .pipe( writeStream )
    
    

自定义模块

  1. 先定义一个 变量, 变量值可以随意

  2. 导出模块

    module.exports = 变量名

    module.exports = {
    变量名
    }

  3. 导入
    如果是第一种方式导出 , var 变量名 = require( 相对路径 )

    如果是第二种方式导出, var { 变量名 } = require ( 相对路径 )

自定义模块上传 npmjs.com 过程

  1. 创建package.json

  2. http://npmjs.com 上注册账号

  3. 激活账号( npmjs.com会发送一个邮件给你的注册邮箱 )

  4. 使用命令登录npmjs.com ( 登录前将你的源从淘宝源 切到 npmjs)

    • 问题 : 如何切换源呢?
    • 解决: 使用 nrm 切换
    • nrm 安装 $ npm i nrm -g
    • nrm 安装完成,输入 nrm ls 查看当前使用的源,nrm use npm 切换到npmjs,然后登录
      $ npm adduser
  5. 如果登录成功, 提示为: Logged in as yanyabing on https://registry.npmjs.org/.

  6. 发布包到npmjs
    $ npm publish

  7. 在npmjs官网查看包有没有发送上去

  8. 下载包来使用一下
    $ npm i 包名称 -S / -D

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值