您的当前位置:首页正文

node模块

来源:图艺博知识网

node

模块

  • 内置模块
    • http ( creatServer)
    • fs (resdFileSync,writeFileSync)
    • url
  • 自定义模块
    我们自己定义的模块
    在node环境中,我们在当前的项目中创建一个js文件,就相当于创建了一个模块,例如:新建一个a.js就相当于创建了一个a模块
    如果需要提供一些方法给其他的模块需要通过module.exports把方法导出,例如:在A模块中写 批量导出:module.exports={fn:fn} 单个导出:module.exports.fn=fn
    创建一个js就是自定义一个模块,在模块中需导出
function fn(){
  console.log('this is A module')
}
module.exports={fn:fn};
  • 第三方模块
    别人写好的模块,需要使用npm管理
    npm install less 安装模块
    npm uninstall less 卸载模块

导入模块

var less=require('less');
var fs=require('fs');
less.render(fs.readFileSync("./1.less","utf-8"),{compress:true},function(error,output){
  fs.writeFileSync("./1.css",output.css,"utf-8")
})
把第三方模块导入到js中

三个常用的node内置模块

var http=require('http');
var fs=require('fs');
var url=require('url');
//url模块中提供了一个方法url.parse() 是用来解析url地址的
  • http
var server =http.createServer(function(request,response){
  //当客户端向服务器端的当前服务(端口号是80这个服务)发送一个请求,并且当前服务已经成功收到这个请求后执行这个回调函数
  //request(请求):存放的是所有客户端的请求信息,包含客户端通过问号传参的方式传递给服务器的数据内容
  //response(响应):提供了向客户端返回内容和数据的方法
  console.log(request.url);
  //request.url:存放的是客户端请求的文件资源的目录和名称以及传递给服务器的数据,例如:客户端请求的地址:http://localhost/index.html?name=123&age=456,我们服务器通过request.url获取到的是:/index.html?name=123&age=456
  var urlObj=url.parse(require.url,true);
  var pathname=urlObj.pathname;
  var query=urlObj.query;
  if(pathname=='/1.html'){
    //根据请求的url地址(具体是根据地址中的pathname)获取到对应资源文件中的源代码
    var con=fs.readFileSync('./1.html','utf-8')//fs.readFileSync([path+name],[encode])同步读取指定文件中的内容(同步读取:文件中的内容读取不完不执行下面的操作,只有都读取出来才会执行后续的操作)
    //response.write:向客户端返回内容
    //response.end():告诉服务器响应结束
    response.write(con);
    response.end()
  }
  
});
server.listen(80,function(){//为这个服务监听一个端口
  
  //当服务创建成功,并且端口号监听成功后执行回调
  console.log('server is success , listening on 80 port!')
}); 

服务创建成功后如何向服务器端发送请求

  • 在浏览器中输入:端口号 http默认是80端口号
  • 在浏览器中输入http://本机ip地址:端口号
var url=require('url');
var str='http://localhost:80/index.html?name=123&age=456';
console.log(url.parse(str))
url.parse(str)
Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'localhost:80',
  port: '80',
  hostname: 'localhost',
  hash: null,
  search: '?name=123&age=456',
  query: 'name=123&age=456',
  pathname: '/index.html',
  path: '/index.html?name=123&age=456',
  href: 'http://localhost:80/index.html?   name=123&age=456' }

  console.log(url.parse(str,true))
  //增加true后,query中存储的是经过处理解析后的结果,把传递进来的数据以键值对的方式进行存储
  Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'localhost:80',
  port: '80',
  hostname: 'localhost',
  hash: null,
  search: '?name=123&age=456',
  query: { name: '123', age: '456' },
  pathname: '/index.html',
  path: '/index.html?name=123&age=456',
  href: 'http://localhost:80/index.html?name=123&age=456' }


Top