Gulp:如何更改文件的修改时间

use*_*304 11 node.js gulp

我有下面的gulp任务和每次运行此任务(在browsersync之前)我想更改一个文件的最后修改时间(该文件没有任何变化,我只需要更改上次修改的时间 - 替代shell"touch"命令).有人可以告诉我,最简单的方法是什么?谢谢!

gulp.task('sass', function() {

    return sass(pkg.sass.dir, {sourcemap: true, precision: 10}) 
        .on('error', function (err) { 
            onError(err);
        })
        .pipe(autoprefixer({
            browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: true
        }))
        .pipe(gulp.dest(pkg.css.dir))
        .pipe(browsersync.reload({stream:true}));
});
Run Code Online (Sandbox Code Playgroud)

Pet*_*ons 8

使用核心fs模块的fs.utimes函数,该函数是与Unix touch命令类似的节点.您传递路径,如果您传递a new Date()作为mtime参数,那应该可以解决问题.


Wra*_*nny 8

gulp-touch-cmd并且gulp-touch从 Gulp 4 开始似乎不起作用,所以我写了这个有效的小管道函数。( npm add through2)

const through2 = require( 'through2' );    

// example
    .pipe( through2.obj( function( file, enc, cb ) {
        let date = new Date();
        file.stat.atime = date;
        file.stat.mtime = date;
        cb( null, file );
    }) )
    .pipe( gulp.dest( '.' ) )
Run Code Online (Sandbox Code Playgroud)

编辑:一个更好的,可重用的例子

...
const through2 = require( 'through2' );    

const touch = () => through2.obj( function( file, enc, cb ) {
    if ( file.stat ) {
        file.stat.atime = file.stat.mtime = file.stat.ctime = new Date();
    }
    cb( null, file );
});

...

gulp.task( 'sass', function() {
    return gulp.src( pkg.sass.dir )
        .pipe( sourcemaps.init() )
        .pipe( sass() )
        .pipe( postcss() )
        .pipe( sourcemaps.write() )
        .pipe( touch() )
        .pipe( gulp.dest( pkg.css.dir ) );
});
Run Code Online (Sandbox Code Playgroud)


小智 5

该插件咕嘟咕嘟一饮而尽触摸-FD固定的咕嘟咕嘟4兼容性问题一饮而尽点触控

npm install --save-dev gulp-touch-fd@funkedigital/gulp-touch-fd
Run Code Online (Sandbox Code Playgroud)

例子:

const {src, dest} = require('gulp');
const touch = require('gulp-touch-fd');

function copyAndTouch() {
  return src('./src/**/*')
    .pipe(dest('./dest'))
    .pipe(touch());
};

exports.copyAndTouch = copyAndTouch
Run Code Online (Sandbox Code Playgroud)