1. 程式人生 > >【node.js】簡易專案自動化構建

【node.js】簡易專案自動化構建

更多內容訪問:

前言:我們可以用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) });