前言
node的内置模块有哪些?
以下是本篇文章正文内容,下面案例可供参考
一、http模块
代码如下(示例):
// 载入 http 模块
var http=require("http");
// 创建 I/O服务 ==请求/应答 ===/ http服务器
http.createServer(function(req,res){
res.write("<h1>hello world</h1>");
res.write("<h2>node</h2>");
res.end(); //应答结束
}).listen(3000); //监听端口
二、url模块
代码如下(示例):
//将url 字符串 转为 url 对象,第二个参数 为true会将query转为对象
url.parse("http://127.0.0.1:3000/one?page=1&limit=3#top",true);
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: '127.0.0.1:3000',
port: '3000',
hostname: '127.0.0.1',
hash: '#top',
search: '?page=1&limit=3',
query: [Object: null prototype] { page: '1', limit: '3' },
pathname: '/one',
path: '/one?page=1&limit=3',
href: 'http://127.0.0.1:3000/one?page=1&limit=3#top'
}
三、fs模块
fs模块就是文件系统模块,负责读写文件:
fs.readFile(文件地址,回调函数) 异步读文件
fs.writeFile(文件地址,写入内容,回调函数) 异步写文件
代码如下(示例):
fs.readFile("./user.txt",function(err,data){
// console.log( typeof data.toString());
var d=JSON.parse(data.toString())
d.arr.push(q)
d=JSON.stringify(d);
fs.writeFile("./user.txt",d,function(err){
if(err){
res.end("500---")
}else{
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
res.end(d)
}
})
})