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 …


This content originally appeared on DEV Community and was authored by Mattia Zanella

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
...

And we need to reach this result:

output |
       foo.mp3
       another-foo.mp3
       bar.mp3
       another-bar.mp3
...

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/
...

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

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'

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

Pay attention to these lines:

     const fileFormat = path.split('.').pop()
     const isMP3 = fileFormat === 'mp3'
     if (!isMP3) return

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)

Some logs

This should avoid you some boring manual stuff ?


This content originally appeared on DEV Community and was authored by Mattia Zanella


Print Share Comment Cite Upload Translate Updates
APA

Mattia Zanella | Sciencx (2021-04-27T13:08:56+00:00) Batch with Node.js. Retrieved from https://www.scien.cx/2021/04/27/batch-with-node-js/

MLA
" » Batch with Node.js." Mattia Zanella | Sciencx - Tuesday April 27, 2021, https://www.scien.cx/2021/04/27/batch-with-node-js/
HARVARD
Mattia Zanella | Sciencx Tuesday April 27, 2021 » Batch with Node.js., viewed ,<https://www.scien.cx/2021/04/27/batch-with-node-js/>
VANCOUVER
Mattia Zanella | Sciencx - » Batch with Node.js. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/27/batch-with-node-js/
CHICAGO
" » Batch with Node.js." Mattia Zanella | Sciencx - Accessed . https://www.scien.cx/2021/04/27/batch-with-node-js/
IEEE
" » Batch with Node.js." Mattia Zanella | Sciencx [Online]. Available: https://www.scien.cx/2021/04/27/batch-with-node-js/. [Accessed: ]
rf:citation
» Batch with Node.js | Mattia Zanella | Sciencx | https://www.scien.cx/2021/04/27/batch-with-node-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.