更多内容访问:
前言:我们可以用node.js,“读”“写”“执行”磁盘和服务器中的文件。
一、简易项目自动化构建代码
var projectData = { 'name' : 'subject', 'fileData' : [ { 'name': 'css', 'type': 'dir' },{ 'name': 'js', 'type': 'dir' },{ 'name': 'images', 'type': 'dir' },{ 'name': 'index.html', 'type': 'file', 'content' : '<html>\n\t<head>\n\t\t<title>首页</title>\n\t\t<meta charset="utf-8">\n\t</head>\n\t<body>\n\t\t<h1>hello</h1>\n\t</body>\n</html>' } ] }; var fs = require('fs'); fs.mkdirSync(projectData.name); //创建项目名称为'subject'的文件夹 projectData.fileData.forEach(function(item){ item.path = projectData.name + '/' + item.name; //给将要在'subject'里创建的文件夹,添加subject/..的前缀 item.content = item.content || ''; switch(item.type){ case 'dir': fs.mkdirSync(item.path); //创建文件夹 break; case 'file': fs.writeFileSync(item.path,item.content); //创建文件,并写入内容 break; } });
二、用node执行代码
①、就可以在该js文件的同目录下创建一个名字为“subject”的文件夹。
②、然后该文件夹下有css,js,images文件夹,并且有个index.html文件
可以创建更多自己项目中常用到文件夹和其他文件。
三、代码解析
1、require('fs'),引用node提供的文件系统模块
2、操作文件夹(文件夹名字假设为subject)
①、同步创建文件夹 fs.mkdirSync('subject' );
②、异步创建文件夹 fs.mkdir('subject', function(){});
③、同步删除文件夹 fs.rmdirSync('subject');
④、异步删除文件夹 fs.redir('subject', function(){});
⑤、查看文件夹是否存在
fs.exists('subject',function(cb){ console.log(cb); //如果存在返回true });
⑥、读取文件夹
fs.readdir('subject',function(err, fileList){ console.log(fileList); fileList.forEach(function(item){ fs.stat('subject/'+item,function(err, info){ //读取文件详细信息 //console.log(arguments); //mode = 33206 表示文件类型 //mode = 16822 表示文件夹 switch (info.mode){ case 16822: console.log('[文件夹]' + item); break; case 33206: console.log('[文件]' + item); break; default: console.log('[其他类型]' + item); } }); }); });
2、操作文件(假设文件名为index.html,内容为<h1>hello</h1>)
①、同步创建文件 fs.writeFileSync('index.html','<h1>Hello</h1>' );
②、异步创建文件 fs.writeFile('index.html','<h1>Hello</h1>',functino(){});
③、同步在文件数据尾部添加内容 appendFileSync('index.html','<h1>Hello</h1>') ;
④、异步在文件数据尾部添加内容 appendFile('index.html','<h1>Hello</h1>',function(){}) ;
⑤、检测文件是否存在
fs.exists('index.html',function(cb){ console.log(cb); //如果存在返回true });
⑥、同步读取文件全部内容 fs.readFileSync('index.html', 'binary'); //‘binary’表示二进制的方式读取
⑦、异步读取文件全部内容
fs.readFile('index.html','binary',function(err, fileContent){ //'binary'表示二进制的方式读取 });
⑧、同步删除文件 fs.unlinkSync('index.html');
⑨、异步删除文件 fs.unlink('index.html',function(){});
⑩、读取文件信息 fs.stat('index.html',function(){ console.log(arguments) });