Search code examples
javascriptnode.jsbashdirectorysequential

Sequentially numbered directories creation in NodeJS


I want to create sequential numbered directories given the max() existing one + 1, in Javascript - NodeJS.

For example if current dir has:

screenshots/ch33-001/
screenshots/ch33-002/
screenshots/ch33-003/

Script should create the next one:

screenshots/ch33-004/

If no directory exists yet, script should create the first:

screenshots/ch33-001/

I was using this in bash script but now i have to move this logic into nodejs:

browser=ch33
num=1
dirname=.
while [[ -d $dirname ]]; do
    let num++
    dirname=$(echo $browser- $num | awk '{ printf("%s%03d\n", $1, $2) }')
done
mkdir screenshots/$dirname

Solution

  • Here is how I would do it:

    var fs = require('fs');
    var path = require('path');
    
    var screenshot_dir = './screenshots';
    
    var max = 0;
    fs.readdirSync(screenshot_dir).forEach(function (file) {
        var match = file.match(/^ch33-(\d{3})$/);
        if (!match)
            return;
    
        var num = Number(match[1]);
        if (num > max)
            max = num;
    });
    
    fs.mkdirSync(path.join(screenshot_dir,
                           "ch33-" + ("000" + (max + 1)).slice(-3)));