Reorganize files with sequential numbers using Gulp, starting from the highest number within the directory

I am looking to create a gulp task that moves files from one folder to another while renaming them with sequential numbers.

Here is the current task I have:

var index = 0;


gulp.task("jpg", function () {
    return gulp.src('img/new/**.{jpg,JPG}')
            .pipe(chmod(666))
            .pipe(rename(function (path) {
                path.basename = (index++);
                path.dirname += "/full_size";
                path.extname = ".jpg";
                return path;
            }))
            .pipe(gulp.dest('img/gallery'));
});

I would like to know how to write a script that checks for the highest number already in the destination folder and updates the var index accordingly to prevent file overwriting.

Answer №1

My experience with gulp is limited, but I believe there are more efficient ways to utilize it. I experimented with a different directory structure and managed to make it work for me. Firstly, you need to require the file system module by adding this line at the top of your gulp file:

const fs = require('fs');

Below is the revised gulp task:

/**
 * Gulp task modified by Georgi Naumov
 * <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdbd3d2ddc9d1d3cafcdbd1ddd5d092dfd3d1">[email protected]</a> for contacts
 * and suggestions.
 */
gulp.task("jpg", function () {
    var files = fs.readdirSync('img/gallery/full_size/'), index = 0;

    // Finding the maximum index inefficiently
    files.forEach(function (currentFile) {
        var currentIndex = (/^([0-9]+)\.jpg$/i.exec(currentFile) || [, false])[1];
        if (currentIndex && parseInt(currentIndex) >= index) {
            index = ++currentIndex;
        }
    });

    return gulp.src('img/new/**.{jpg,JPG}')
        .pipe(chmod(666))
        .pipe(rename(function (path) {
            path.basename = (index++);
            path.dirname += "/full_size";
            path.extname = ".jpg";
            return path;
        }))
        .pipe(gulp.dest('img/gallery'));
});

If performance is crucial, a shell command could be used to fetch the file with the highest number, but this would sacrifice platform independence.

Edit:

I believe isolating the logic to find the maximum number into a package is a good approach. Therefore, I have created an npm package which can be installed and utilized.

To install, run:

npm install --save npm-max-dir-index

After installation, you can incorporate it as follows:

const maxDirIndex = require('npm-max-dir-index');

/**
 * Gulp task modified by Georgi Naumov
 * <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e5edece3f7efedf4c2e5efe3ebeeace1edef">[email protected]</a> for contacts
 * and suggestions.
 */
gulp.task("jpg", function () {
    var index = maxDirIndex('img/gallery/full_size/', '^([0-9]+)\.jpg$');    

    return gulp.src('img/new/**.{jpg,JPG}')
        .pipe(chmod(666))
        .pipe(rename(function (path) {
            path.basename = (index++);
            path.dirname += "/full_size";
            path.extname = ".jpg";
            return path;
        }))
        .pipe(gulp.dest('img/gallery'));
});

Please refer to the updated package documentation here:

https://www.npmjs.com/package/npm-max-dir-index

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the completion of multiple asynchronous calls in AngularJS: A guide

I have a SQLService running on my PhoneGap/AngularJS app that processes a long array of Guidelines with DB transactions. How can I indicate when the final transaction is completed? I envision a flow like this: In the controller, call `SQLService.ParseJS ...

Utilizing Vue-cli 3: Incorporating static assets with a specific path

My application is located at: https:/firstpath.com/firstsubfolder/app.html When using relative paths, my static assets are being loaded from: https:/firstpath.com/firstsubfolder/img/image.png Is there a way to specify a specific path for my static asse ...

Using Rails to render a partial through Ajax and then modifying that partial using JavaScript

My application allows users to click a button that triggers the appearance of a text field using ajax. After the text field appears, I am attempting to focus on it. Interestingly, $("#my-textfield").focus() works perfectly when executed in the console, b ...

The React state update function is malfunctioning

const [cartItems, setcartItems] = useState([] as Product[]); const addItemToCart = (product: Product) => { setcartItems((preCartItems) => { const updatedcart = [...preCartItems]; if(!updatedcart.length) updatedcart.push(product) ...

Analyzing memory consumption by an individual function in a Node.js environment

Our current experiment involves measuring the memory usage of specific functions. Initially, we attempted to utilize process.memoryUsage().heapUsed before and after calling the function, but encountered issues due to the behavior of the garbage collector. ...

Encountering a dependency tree error while attempting to execute the command "npm i @angular/cdk."

I attempted to execute the following command npm i @angular/cdk Unfortunately, I encountered this error : npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection ...

Can you identify the issue with the phase control in my sine wave program?

I have recently developed an interactive sine wave drawing web application. Below is the code snippet for reference: const canvas = document.getElementById("canvas"), amplitude_slider = document.getElementById("amplitude_control"), wavelength_slider ...

discovering the absence of any letters within an array

Looking for a way to find multiple missing letters in an array? Check out this code snippet: function missingLetters(str) { var nums = str.split('').map(function(letter){ return letter.charCodeAt(); }) var result = []; for(va ...

Transforming control of execution seamlessly between two interactive functions in nodejs

Two functions are used to take input from the CLI using process.stdin. The issue arises when one function is done taking input, as a similar function is called. However, while the control shifts to the second function, the first function continues executin ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

Unable to modify the name of an element's class due to restrictions in JavaScript

I am trying to switch the class of an element from score -box1 to score -box1.-active. I defined a constant $target in order to access the class score -box1, however it is not functioning as expected. const $target = document.getElementByClassname('sc ...

Move each four-character IT value to a new line

const maxNumLength = 4; event = jQuery.Event("keypress") event.which = 13 $('#input').on('input focus keydown keyup', function() { const inputValue = $(this).val(); const linesArray = inputValue.split(/(&bsol ...

Is there a way to display "Loading" text upon clicking a button using angular.js?

Check out this unique progress bar code snippet: <svg class="center-block progress-bar-round" width="200" height="200"> <circle cx="100" cy="100" r="90" fill="none" stroke=& ...

Stop the execution of the JavaScript function when clicked

Greetings, as a newcomer to the realm of JavaScript and AJAX, I am seeking assistance with a specific function on this page. The concept revolves around triggering different JavaScript functions based on user interaction with an image map. Initially, when ...

I'm having trouble with my react-big-calendar not updating when I switch between day, month, or week views -

Why won't my calendar change to the week view when I click on that section? https://i.stack.imgur.com/gh2aO.png In the screenshot above, my default view is set to month, but when I attempt to switch to week, it only highlights the option without cha ...

Obtain the controller name from the current scope

I am trying to assign a controller named in the scope of another controller JavaScript file: .controller('PageCtrl', [ '$http', '$scope', '$routeParams', '$location', function($http, $scope, $ro ...

What causes the ERR_HTTP_INVALID_STATUS_CODE error to appear on my screen?

For my first project as a beginner, I decided to create a basic calculator which performs calculations on the server. Below is the code snippet from my .js file: const express = require("express"); const bodyParser=require("body-parser"); var app = expres ...

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

Selecting a specific row in JqGrid based on a data value

I need to automatically select a row when the grid is loading, based on the data value of a specific column in that row. I am looking to select the row with invoice number IVAXVL18066996 (attached below). https://i.sstatic.net/2mC94.png I have been resea ...