gulp監聽文件變化,並拷貝到指定目錄

暫時不支持目錄修改、建立、刪除。php

var gulp = require('gulp');
var fs = require('fs');
var path = require('path');
var less = require('gulp-less');
var sass = require('gulp-sass');
var minifycss = require('gulp-minify-css');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var tinylr = require('tiny-lr');
var server = tinylr();
var port = 1234;

// browser-sync
var browserSync = require('browser-sync');

// 建立多層目錄
function mkdirs(dirname, mode, callback){
    fs.exists(dirname, function (exists){
        if(exists){
            callback();
        }else{
            //console.log(path.dirname(dirname));
            mkdirs(path.dirname(dirname), mode, function (){
                fs.mkdir(dirname, mode, callback);
            });
        }
    });
}

// 拷貝文件
function copyfile(oldPath, newPath) {
    console.log('複製'+oldPath+' -> '+newPath);
    
    var stat = fs.lstatSync(oldPath);
    if(stat.isDirectory()) {
        console.log(oldPath+'是目錄');
        return false;
    }
    
    var readStream = fs.createReadStream(oldPath);
    var writeStream = fs.createWriteStream(newPath);
    readStream.pipe(writeStream);
    readStream.on('end', function () {
        console.log('copy end');
    });
    readStream.on('error', function () {
        console.log('copy error');
    });
}

gulp.task('default', function() {
    
});

gulp.task('css', function() {
    return gulp.src('src/*.css')      //壓縮的文件
        .pipe(gulp.dest('target/css'))   //輸出文件夾
        .pipe(minifycss());   //執行壓縮
});

// 編譯Sass
gulp.task('sass', function() {
    gulp.src('./src/css/*.scss')
        .pipe(sass())
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifycss())
        .pipe(gulp.dest('target/css'));
});

gulp.task('js', function() {
    return gulp.src('./src/js/*.js')
        .pipe(gulp.dest('target/js'))    //輸出main.js到文件夾
        .pipe(rename({suffix: '.min'}))   //rename壓縮後的文件名
        .pipe(uglify())    //壓縮
        .pipe(gulp.dest('target/js'));  //輸出
});

gulp.task('html', function() {
    return gulp.src('./src/*.php')
        .pipe(gulp.dest('target/'));  //輸出
});

// 監放任務 運行語句 gulp watch
gulp.task('watch',function(){
    server.listen(port, function(err){
        if (err) {
            return console.log(err);
        }
        
        //拷貝修改過的文件
        gulp.watch('src/**/**', function(e) {
            console.log(e);
            var oldPath = e.path;
            var newPath = oldPath.replace('\\src\\', '\\target\\');
            var newDirPathTemp = newPath.split("\\");
            var currentPath = fs.realpathSync('.');
            var newDirPath = [];
            for(var i = 0; i < newDirPathTemp.length-1; i++) {
                newDirPath[i] = newDirPathTemp[i];
            }
            newDirPath = newDirPath.join("\\");
            newDirPath = newDirPath.replace(currentPath, '');
            newDirPath = newDirPath.replace(/\\/g, "/");
            newDirPath = newDirPath.replace("/", "./");
            //console.log('當前路徑'+newDirPath);
            
            // 修改或增長時
            if('added' == e.type || 'changed' == e.type || 'renamed' == e.type) {
                // 判斷目錄是否存在,不存在則建立
                fs.exists(newDirPath, function(exists){ 
                    if(exists){ 
                        //console.log("文件夾存在");
                        copyfile(oldPath, newPath);
                    } else {
                        //console.log("文件夾不存在,則建立目錄");
                        mkdirs(newDirPath);
                        
                        // 延時,等待目錄建立完成
                        setTimeout(function(){
                            copyfile(oldPath, newPath);
                        }, 200);
                    }
                });
            } else if('deleted' == e.type) { //刪除
                fs.unlink(newPath, function(err){
                    console.log('刪除'+newPath+err);
                });
            }
        });

        // 監聽sass
        gulp.watch('src/css/*.scss', function(){
            gulp.run('sass');
        });

        // 監聽js
        gulp.watch('./src/js/*.js', function(){
            gulp.run('js');
        });
        
        // 監聽html
        gulp.watch('./src/*.php', function(){
            gulp.run('html');
        });
        
    });
    
    // 實時同步到瀏覽器
    browserSync.init(['target/css/*', 'target/js/*', 'target/*.html', 'target/*.php'], {
        /* 靜態服務
        server: {
            baseDir: "target"
        }
        */
        
        // 代理模式
        proxy: "dz.com"
    });
    
});
相關文章
相關標籤/搜索