DEV Community

Cover image for Batch with Node.js
Mattia Zanella
Mattia Zanella

Posted on

8 1

Batch with Node.js

Premise

Let's say that your aunt comes to you asking a favor.

She has this pen drive with A LOT of folders containing mp3s and by what she believes her car cannot read recursively all the folders so she needs one root folder containing all the mp3s.

The USB drive is structured as below:

songs |
      folder_1 |
               foo.mp3
               another-foo.mp3
      folder_2 |
               bar.mp3
               another-bar.mp3
...

Enter fullscreen mode Exit fullscreen mode

And we need to reach this result:

output |
       foo.mp3
       another-foo.mp3
       bar.mp3
       another-bar.mp3
...
Enter fullscreen mode Exit fullscreen mode

Given this overview, you have two option to do this:

  • Do it manually.
  • Leave a like ❤️ to this post.

To start we're gonna create a folder, let's call it batch-node.
Inside that folder I've copied the songs folder (above) and I've created an index.js file.
So this is now my batch-node structure:

batch-node |
           index.js
           songs/
...
Enter fullscreen mode Exit fullscreen mode

For this purpose we'll use fs-extra since copy/paste seems like not supported by fs API.

Just add it:

yarn add fs-extra
Enter fullscreen mode Exit fullscreen mode

Let's starting coding.

// index.js

/**
 * fs-extra adds file system methods that aren't included in the native
 * fs module and adds promise support to the fs methods.
 */
const fs = require("fs-extra");

const MP3_DIRECTORY = './songs'
const OUTPUT = './output'
Enter fullscreen mode Exit fullscreen mode

Be carefull, do not create output/ folder since fs-extra will handle this for us otherwise it won't work.

The script is composed by 2 main functions:

  • a readDirectory to, of course, read a folder and its content.
  • and a copyToDestination function to copy our song to the folder destination.

Let's add these functions to our index.js:

const copyToDestination = ({ path, file }) => {
    try {
        const fileFormat = path.split('.').pop()
        const isMP3 = fileFormat === 'mp3'
        if (!isMP3) return

        // @see https://stackoverflow.com/a/40019824
        fs.copySync(path, `${OUTPUT}/${file}`)
        console.log(`${ file } has been copied to ${ OUTPUT }`)
    } catch(error) {
        console.error({ error })
    }
}

const readDirectory = dir_name => {
    fs.readdir(dir_name,
        { withFileTypes: false },
        (error, files) => {
            try {
                files.forEach(file => {
                    const path = `${dir_name}/${file}`
                    // @see https://nodejs.org/docs/latest/api/fs.html#fs_stats_isdirectory
                    const isDir = fs.lstatSync(path).isDirectory()
                    const config = { file, path }

                    return isDir ? readDirectory(path) : copyToDestination(config)
                })
            } catch (error) {
                console.error({ error });
            }
        }
    )
}

Enter fullscreen mode Exit fullscreen mode

Pay attention to these lines:

     const fileFormat = path.split('.').pop()
     const isMP3 = fileFormat === 'mp3'
     if (!isMP3) return
Enter fullscreen mode Exit fullscreen mode

Since we have different types of files inside folders (like covers album, ini files and many more) we're returning the function to totally ignore these kinds of file.

Finally we just have to lunch our function at the end of our index.js:

readDirectory(MP3_DIRECTORY)
Enter fullscreen mode Exit fullscreen mode

Some logs

This should avoid you some boring manual stuff 🙃

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay