Fork me on GitHub

node前端自动化

一、前端自动化-项目构建

我们平时写代码,喜欢建一个project,然后里面是css、js、images文件,以及index.html,而node可以自动化构建好项目,如下:

 

/**
 * Created by 毅 on 2015/9/20.
 */

var projectData = {

    'name' : 'project',
    '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</title>\n\t</head>\n\t<body>\n\t\t<h1>Hello</h1>\n\t</body>\n</html>',
        }
    ]

};

var fs = require('fs');

if ( projectData.name ) {
    fs.mkdirSync(projectData.name);

    var fileData = projectData.fileData;

    if ( fileData && fileData.forEach ) {

        fileData.forEach(function(f) {

            f.path = projectData.name + '/' + f.name;

            f.content = f.content || '';

            switch (f.type) {

                case 'dir':
                    fs.mkdirSync(f.path);
                    break;

                case 'file':
                    fs.writeFileSync(f.path, f.content);
                    break;

                default :
                    break;

            }

        });

    }

}

 

 二、前端自动化--监听文件的变化

在上面的自动生成的project文件夹里面再建一个source文件夹。下面的代码就是监听source文件夹的任何变化,不管是新建文件还是往新建文件中加入内容。它都会合并到js/index.js中去。

var fs = require('fs');

var filedir = './project/source';

fs.watch(filedir, function(ev, file) {

    //console.log(ev + ' / ' + file); // 这里不需要判断file是否有内容

    //只要有一个文件发生了变化,我们就需要对这个文件夹下的所有文件进行读取,然后合并

    fs.readdir(filedir, function(err, dataList) {

        var arr = [];

        console.log(dataList);

        dataList.forEach(function(f) {

            if (f) {
                var info = fs.statSync(filedir + '/' + f);

                //console.log(info);

                if (info.mode == 33206) {
                    arr.push(filedir + '/' + f);
                }
            }

        });

        //console.log(arr);

        //读取数组中的文件内容,并合并

        var content = '';
        arr.forEach(function(f) {
            var c = fs.readFileSync( f );
            //console.log(c);

            content += c.toString() + '\n';

        });

        console.log(content);

        fs.writeFile('./project/js/index.js', content);

    });

})

 

posted on 2016-05-26 21:11  雨为我停  阅读(241)  评论(0编辑  收藏  举报