1、require:引入模块
(1)自定义模块:自己写的每一个文件就是一个自定义模块。
require('./hello.js')
(2)第三方模块:别人写的模块,使用npm安装别人的模块。
nmp install 包名称
(3)系统模块:fs,http等系统提供的模块。
2、exports:暴露模块
(1)hello.js暴露:
var name = "zhangsan"; //暴露模块的name module.exports.name = name;(2)main.js引入:
var hello = require('./hello.js'); var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"}); response.write(hello.name) response.end(); }).listen(8888);1、创建http模块
var http = require("http");2、获取推流的数据
http.get('http://www.baidu.com/',function(res){ //真正拿到的东西是需要data事件的 res.on('data',function(txt){ console.log(txt); }); }) http.createServer(function(request, response) { }).listen(8888);3、获取网页数据
http.get('http://www.baidu.com/', function (res) { var html = ''; //1、data事件 res.on('data', function (txt) { // console.log(txt.toString()); // console.log('-------') //字节数 console.log(txt.length) html+=txt; }); //2、end事件 res.on('end',function () { console.log(html) }) })1、进入文件系统模块
const fs = require('fs');2、使用fs系统模块的方法读取文件,异步读取
fs.readFile('../file.txt',(err, data) => { console.log(err); console.log(data.toString()); })3、同步方法
const file = fs.readFileSync('../file.txt'); console.log(file.toString())管道可以实现文件的复制。