npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

batch-file-renamer

v0.1.3

Published

Module to simplify writing node.js commandline applications that rename groups of files

Downloads

14

Readme

Batch File Renamer

A module to make writing node.js commandline applications that rename files easier to write.

Basic Example

To create a trivial application using Batch-File-Renamer:

#!/usr/bin/env node
// lowercaser.js

var batchFileRenamer = require('batch-file-renamer');

batchFileRenamer({
    rule: function (filename) {
        return filename.toLowerCase()
    }
});

Can then be used as follows:

$ ls
FileName01.TXT fileNAME02.txt FiLeNaMe.TxT

$ ./lowercaser.js *

$ ls
filename01.txt filename02.txt filename.txt

To prevent a file from being renamed, you can simply have the rule return null and it won't rename that file.

Rules can be synchronous, node callbacks, or promises.

CLI Options

It is possible to pass in CLI Options to batch renamer for extending the commandline flags it accepts:

// example.js
batchFileRenamer({
    rule: rule,
    cliOptions: {
        options: {
            foo: { alias: 'F', description: 'Are you foo or not?', type: 'boolean' }
        }
    }
})

And we can see this in the help generated.

$ ./example.js -h
Options:
  --foo, -F           Are you foo or not?                              [boolean]
  --colour            Colour logging                   [boolean] [default: true]
  --verbose, -v       Verbose logging                                  [boolean]
  --quiet             Only log errors                                  [boolean]
  --silent            No logging                                       [boolean]
  --force, -f         Overwrite existing files                         [boolean]
  --recursive, -r     Name files in directory recursively              [boolean]
  --interactive, -i   Prompt for file change                           [boolean]
  --backup            Create backup of file                            [boolean]
  --error-on-missing  Fail if any source file missing                  [boolean]
  --version, -V       Show version number                              [boolean]
  --help, -h          Show help                                        [boolean]

Uses yargs in the back, so you should be able to pass anything you would pass to yargs.options method.

Pre/Post/onError Commands

Add pre, post and onError hooks. Post hook only runs on successful renaming.

// example.js
batchFileRenamer({
    pre: function () {
        db.openConnection();
    },
    rule: rule,
    post: function () {
        db.closeConnection();
    },
    onError: function () {
        db.closeConnection();
    }
})

The pre and post options may be async (promises or callback), whilst the onError command is synchronous.

Logging

You could just log to stdout using console.log, however this won't respond to the provided verbose, silent, quiet and (hidden) DEBUG flags. A useful logger is provided.

var batchFileRenamer = require('batch-file-renamer');
var logger = batchFileRenamer.logger;

batchFileRenamer({
    pre: function () {
        logger.debug('The application is starting');
        logger.log('Welcome to this amazing application!');
    },
    rule: function (filename) {
        filename = filename.toLowerCase();
        if (filename.length > 100)  {
            logger.warn('That is a long filename');
        }
        if (filename === 'never_gonna_give_you_up') {
            logger.error('Rickrolled');
        }
        return filename;
    }
})

The logger commands can only be used inside the batch-file-renamer process, as they are initialised according to verbosity variables.

By default, warnings and errors are shown, whereas logs are only shown in verbose mode.

Duplicate Destination Handling

By default the application will throw an error if duplicate destinations are provided, however it is also possible to provide a duplicate destination resolver.

This is an example of how you might use it:

var incrementers = {};

batchFileRenamer({
    rule: rule,
    duplicationResolver: function (duplicateDests, srcDestPairs) {
        return srcDestPairs.map(function (pair) {
            var src = pair[0];
            var dest = pair[1];
            var i;
            if (duplicateDests.indexOf(dest) !== -1) {
                if (!incrementers[dest]) {
                    incrementers[dest] = 0;
                } else {
                    incrementers[dest] += 1;
                }
                i = incrementers[dest];
                dest = dest + i;
            }
            return [src, dest];
        })
    }
})

Bare in mind that further duplication checks are not run after this function.

Custom Error Messages

If you throw an error (or return error in promise / node callback) it gets handled by batch-file-renamer's error handler. You can provide your own message simply by throwing an error with your own message.

Also, if you want to provide custom error messages for system errors, you can add them like so:

batchFileRenamer({
    rule: rule,
    errorMessages: {
        ENOMEM: 'Sorry to mention it, but you are out of memory'
    }
})

This relies on the error.code being ENOMEM.