在 gulp 中使用 fs.readdirSync 的正确方法,我该如何整合它?

right approach with fs.readdirSync in gulp and how do i integrate it?

我目前正在单独输入数组,有没有办法读取 'directories'?

我找到了以下代码。这是正确的做法吗?我如何整合它?抱歉,我是 JavaScript 和 Gulp 的初学者。

const testFolder = 'dist/document/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
});
'use strict';

// Modules & Plugins
var gulp = require('gulp');
const image = require('gulp-image');
var $ = require('gulp-load-plugins')();

// the path for example 'document/2006/Art1'
var articlePath = 'document/';

// I am currently entering the arrays individually :-/
let directories = [
  '2006/Art1',
  '2006/Art2',
  '2010/Art1',
  ...
];

gulp.task('gulpTask', function () {
  function singleDirectoryGulpTask(directoryName) {
    return gulp
      .src(articlePath + directoryName + '/media/*.{jpg,jpeg,png,gif}')
      .pipe($.responsive({
        '*.jpg': [
          { width: 400, rename: { suffix: '-4' } },
          { rename: { suffix: '-6' } },
        ],
      }))
      .pipe(image({
       mozjpeg: ['-optimize'], 
       guetzli: ['--quality', 85],
       concurrent: 10, quiet: false
      }))
      .pipe(gulp.dest('dist/'+ articlePath + directoryName + '/media'))
  }

  return merge(articleDirs.map(singleDirectoryGulpTask));
});

稍微猜测一下您要做什么,但这种通用形式有效:

const subDirectories = fs.readdirSync('testFolder');
console.log(subDirectories);


gulp.task('default', (done) => {

// subDirectories.forEach(function (directoryName) {  // don't use

 for (const directoryName of subDirectories) {  // use this

  gulp.src(path.join(articlePath, directoryName, 'media', '*.{jpg,jpeg,png,gif}'))
    // do your stuff
    .pipe(gulp.dest(path.join('dist', articlePath, directoryName, 'media')))
  });
  done();
});

并为

var articlePath = 'document/';  

你不需要尾随 / 因为您将它与 path.join() 一起使用,它会自动包含那些。