nodejs中内置模块fs,path常见的用法说明
readFile
readFileSync同步读取数据
varfs=require('fs');
fs.readFileSync('./a.txt');
readFile异步读取数据
varfs=require('fs');//引入文件
fs.readFile('./a.txt',function(err,data){
//当异步读取完文件数据后执行该回调函数中代码
//err错误对象;
//data数据
if(err){
console.log('读取文件出错');
return;
}
//正常打印数据
console.log(data.toString());
})
console.log('111');
写文件writeFile
writeFileSync同步读取数据
varfs=require('fs');//引入内置模块
fs.writeFileSync("b.txt","我是写入的内容");
writeFile异步读取数据
fs.writeFile('c.txt','我是写入的内容',function(err){
if(err){
console.log('写文件出错');
return;
}
console.log('写文件出错');
})
console.log('111');
练习
varfs=require('fs');//引入文件模块
fs.mkdirSync('./web1804');//同步创建目录;
fs.writeFileSync('./web1804/node1.txt','这是我的学习笔记');
vardata=fs.readFileSync('./web1804/node1.txt');
console.log(data.toString());
fs.mkdir('./web1804_1',function(err){
if(err){
console.log('创建目录失败');
return;
}
console.log('创建目录成功');
})
varisExist=fs.existsSync('./web1804');
拓展
1、文件删除;
2、创建多级目录d:/web1804/javascript/css
3、删除文件目录
4、复制文件
创建目录fs.mkdir
检测是文件还是目录fs.stat
写入追加文件fs.oppendFile
读取目录fs.readdir
重命名rename
删除目录rmdir
删除文件unlink
path
varpath=require('path);
varpsth1="http://www.baidu.com.cn/img.jpg";
varindex=psth1.indexOf('/');
console.log(index);
varlastindex=psth1.lastIndexOf('/');//从后向前获取指定字符在字符串中的序号
varsub=path1.substring(lastindex+1);//substring(index)返回指定序号index后的子字符串
console.log('sub:+'+sub);
path.basename返回路径的最后一部分
varpsth1="http://www.baidu.com.cn/img.jpg"; varimgName=path.basename(path1);//返回路径的最后一部分,个人认为用这个来获取文件名或者URL中带的参数 console.log(imgName);
path.jion
varpaths=path.jion('web1804','html','css');
console.log(paths);//web1804\html\css
path.parse返回路径字符串的对象
varpath1='http://www.baidu.com.cn/img.jpg'; varurl=path.parse(path1); console.log(url);
console.log(_dirname);当前绝对路径
拓展
substring();返回指定序号index后的子字符串;
lastIdexOf从后向前获取指定字符中在字符串中序号;
补充知识:NodeJs内置的url、path、http模块的应用
1.url模块:
//引入url模块
varurl=require("url");
//假设一个网址
varhref="http://www.baidu.com?name=jhh&age=20";
//将网址解析成一个Url对象
varobj=url.parse(href,true);
console.log(obj);
//获取Url对象中的query对象
varquery=obj.query;
console.log("queryName:"+query.name);
console.log("queryAge:"+query.age);
2.path模块:
//引入path模块
varp=require("path");
//自定义绝对路径
varpath="C:\\jhh\\text\\js";
//去掉最后一层
console.log(p.dirname(path));//C:\jhh\text
//取最后一层
console.log(p.basename(path));//js
3.http模块:
//引入http模块
varhttp=require("http");
//创建web服务器
varserver=http.createServer();
//监听请求
server.on("request",function(request,response){
console.log("收到用户请求:"+request.method);
varurl=request.url;
varmsg="";
if(url=="/"){
msg="这是主页"
}elseif(url=="/login"){
msg="这是登录页"
}else{
msg="404";
}
//解决相应乱码
response.setHeader("content-type","text/html;charset=utf-8");
//相应数据
response.write(msg);
//结束相应
response.end();
});
//启动服务器
server.listen(8081,function(){
console.log("服务器启动")
});
以上这篇nodejs中内置模块fs,path常见的用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。