NodeJS中的顺序编号目录创建

时间:2014-03-08 20:26:53

标签: javascript node.js bash directory sequential

我希望在Javascript - NodeJS中给定max()现有的1 + 1创建顺序编号的目录。

例如,如果当前目录有:

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

脚本应该创建下一个:

screenshots/ch33-004/

如果还没有目录,脚本应该创建第一个目录:

screenshots/ch33-001/

我在bash脚本中使用它,但现在我必须将此逻辑移动到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

2 个答案:

答案 0 :(得分:1)

我将如何做到这一点:

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)));

答案 1 :(得分:0)

var fs = require('fs');
var browser = 'ch33';
var build_path = '.';
for (var i=1; fs.existsSync(build_path); i++) {
    build_path = path.join('./screenshots', browser + '-' + helpers.pad(i, 3));
};
fs.mkdirSync(build_path);

为了完整起见:

var helpers = {}; helpers.pad = function(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
};