简体   繁体   English

如何选择最新的文件?

[英]How to select the most recent file?

I need to grab the most recent file with src in every subdirectory. 我需要在每个子目录中使用src获取最新文件。

This is the task I have : 这是我的任务:

gulp.task('compile', function() {
  return gulp.src('src/jade/**/*.js')
    .pipe(jade({pretty: true}))
    .pipe(gulp.dest('dist'));
});

Is there a way to get the freshest JS with gulp src ? 有没有办法让gulp src获得最新鲜的JS?

Well, without really having used gulp so far, what you should do would be something like: 好吧,到目前为止没有真正使用gulp,你应该做的是:

  • Find all the files you wish to compile 找到您要编译的所有文件
  • send them to the src method (which takes a string, or an array of files or a stream) 将它们发送到src方法(它接受一个字符串,或一个文件数组或一个流)

One of my problems was how to handle the glob style path, so for that I installed the glob npm package in my local package.json 我的一个问题是如何处理glob样式路径,所以为此我在我的本地package.json中安装了glob npm包。

What I then did was, get all the files using glob( path, callback ) , filter those according to the last modified using fs.stat and the mtime or mtimeMs and only keeping the last one 我接下来做的是,使用glob( path, callback )获取所有文件glob( path, callback )使用fs.statmtimemtimeMs根据上次修改过滤那些mtimeMs并仅保留最后一个

const { src, dest } = require('gulp');
const glob = require('glob');
const path = require('path');
const fs = require('fs');

async function getFileLastModifiedBy( file ) {
  return new Promise( (resolve, reject) => {
    fs.stat( file, (err, stats) => {
      if (err) {
        reject( err );
        return;
      }
      resolve( stats.mtimeMs );
    });
  } );
}

async function filterByNewest( input ) {
  const filesByModifiedBy = {};
  for (let file of input) {
    let directory = path.dirname( file );
    let lastModifiedBy = await getFileLastModifiedBy( file );
    if (!filesByModifiedBy[directory] || filesByModifiedBy[directory].lastModifiedBy < lastModifiedBy) {
      filesByModifiedBy[directory] = { file, lastModifiedBy };
    }
  }
  return Object.values( filesByModifiedBy ).map( v => v.file );
}

and then you could integrate it with your current workflow like in the following way 然后您可以将其与当前工作流程集成,如下所示

gulp.task('compile', function() {
  return new Promise( (resolve, reject) => {
    glob('src/jade/**/*.js', async function( err, files ) {
      if ( files ) {
        const newest = await filterByNewest( files );
        resolve( 
          src( newest )
            .pipe(jade({pretty: true}))
            .pipe(dest('dist'))
        );
        return;
      }
      reject( err );
    })
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM