user3631047
user3631047

Reputation: 3384

Gulp src order of files

Files in my directory:

1-icon.svg
2-icon.svg
3-icon.svg
10-icon.svg
11-icon.svg
12-icon.svg
20-icon.svg
21-icon.svg
22-icon.svg

Gulp src read them as:

1-icon.svg
10-icon.svg
11-icon.svg
12-icon.svg
2-icon.svg
20-icon.svg
21-icon.svg
22-icon.svg
3-icon.svg

I have tried gulp-sort and gulp-order but none of them gave me the exact order of files like my directory.

Any way to do this?

Upvotes: 2

Views: 1293

Answers (1)

Sergey Mell
Sergey Mell

Reputation: 8040

Yeah, gulp orders file same as strings could be ordered. To manage the ordering you can use gulp-sort plugin. Here is an example, I've done

const gulp = require('gulp'),
    debug = require('gulp-debug'),
    sort = require('gulp-sort'),
    path = require('path');

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

    return gulp.src('./test/*')
        .pipe(debug())
        .pipe(sort(customComparator))
        .pipe(debug())
        .pipe(gulp.dest('./dist'));

});

function customComparator(f1, f2) {
    const f1Name = path.basename(f1.path);
    const f2Name = path.basename(f2.path);
    return Number(f1Name.split('-')[0]) > Number(f2Name.split('-')[0]) ? 1 : -1;
}

Take a look at customComparator function which takes the first part of file name and created an order on the basis of it.

The gulp-debug plugin is used only to see the order of files in the console. So, the result looks as follows. You can see the list of files before and after ordering

$ npx gulp ordering
[18:54:27] Using gulpfile ~/own_projects/untitled/gulpfile.js
[18:54:27] Starting 'ordering'...
[18:54:27] gulp-debug: test/1-icon.svg
[18:54:27] gulp-debug: test/10-icon.svg
[18:54:27] gulp-debug: test/11-icon.svg
[18:54:27] gulp-debug: test/12-icon.svg
[18:54:27] gulp-debug: test/2-icon.svg
[18:54:27] gulp-debug: test/20-icon.svg
[18:54:27] gulp-debug: test/21-icon.svg
[18:54:27] gulp-debug: test/22-icon.svg
[18:54:27] gulp-debug: test/3-icon.svg
[18:54:27] gulp-debug: 9 items
[18:54:27] gulp-debug: test/1-icon.svg
[18:54:27] gulp-debug: test/2-icon.svg
[18:54:27] gulp-debug: test/3-icon.svg
[18:54:27] gulp-debug: test/10-icon.svg
[18:54:27] gulp-debug: test/11-icon.svg
[18:54:27] gulp-debug: test/12-icon.svg
[18:54:27] gulp-debug: test/20-icon.svg
[18:54:27] gulp-debug: test/21-icon.svg
[18:54:27] gulp-debug: test/22-icon.svg
[18:54:27] gulp-debug: 9 items
[18:54:28] Finished 'ordering' after 72 ms

Upvotes: 5

Related Questions