OS模块
提供一些系统操作函数
常用实例
var os = reqiure('os');
console.log(os.endianness()); //cpu字节序,可能返回BE或者LE
console.log(os.type()); //返回操作系统名:例如Linux,与os.platform()一样功能
console.log(os.totalmem()); //返回内存总量,单位bytes
console.log(os.freemem()); //返回剩余内存,单位bytes
path模块
处理文件路径的工具
var path = require('path');
console.log(path.normalize('test//test2')); //注意我这里写了两个斜杆,normalize就是规范化路径,因此输出test/test2,给了我们一个正确的路径
console.log(path.join('/test','test2')); //连接两个路径,得到 /test/test2
console.log(path.resolve('main.js')); //main.js就是当前的js文件,输出是这个js文件所在的绝对路径,例如: /test/test2/main.js
console.log(path.extname('main.js')); //输出后缀名.js
path还有很多用法,详情可以取查询API
Web模块
web应用架构有四层
1:客户端:这就是我们前端的世界了,浏览器通过http协议向服务器请求数据
后端世界开始
2:server:接受客户端请求,并向服务端发送响应数据
3:business:server的处理程序,例如数据库交互,逻辑运算,调用外部程序等
4:data:一般由数据库组成
var http = require('http');
var fs = require('fs');
var url = require('url');
http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
console.log('request for' + pathname + ' received');
//开启我们存好的index.html文件,pathname里面就包含了,当然代码这样直接用证明index.html和这个js文件在一个文件夹目录下
fs.readFile(pathname.substr(1),function(err,data){
if(err)
{
console.log(err);
response.writeHead(404,{'Content-Type':'text/html'});
}
else{
response.writeHead(200,{'Content-Type':'text/html'});
response.write(data.toString()); //这里由于把html整段输出了,所以就是展示出了一个网站
}
response.end();
})
}).listen(8080);
console.log('Server running at (你运行这段代码的服务器解析的域名):8080/');
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的第一个标题</h1>
<p>我的第一个段落。</p>
</body>
</html>
NodeJS模仿终端进行ajax请求(创建web客户端)
var http = require('http');
var options = {
host : 'localhost', //host类似域名
port : '8080',
path : '/index.html'
};
var callback = function(response){
var body = '';
response.on('data',function(data){
body += data;
});
response.on('end',function(){
console.log(body);
});
}
var req = http.request(option,callback);
req.end();
然后就会输出别人设置好的后端中的index.html