// requirements const path = require('path'); const async = require('async'); const fse = require('fs-extra'); const recursive = require('recursive-readdir'); const progress = require('progress'); // create path for target file function getPathByMetadata(source, output, metadata, callback) { // define directory let filePath = path.normalize(output); if (metadata.albumartist && metadata.albumartist.length > 0) { let tmp; const artistCount = metadata.albumartist.length; for (let counter = 0; counter < artistCount; counter++) { if (counter > 0) { tmp += ' - ' + metadata.albumartist[counter]; } else { tmp = metadata.albumartist[counter]; } } filePath = path.join(filePath, tmp); } else { filePath = path.join(filePath, metadata.artist[0]); } if (metadata.album) { filePath = path.join(filePath, metadata.album); } // define filename let fileName = ''; if (metadata.disk.no) { fileName += frontFill(metadata.disk.no, '0', 2); } if (metadata.track.no) { if (fileName) { fileName += '-' + frontFill(metadata.track.no, '0', 2) + ' '; } else { fileName += frontFill(metadata.track.no, '0', 2) + ' '; } } if (metadata.artist) { fileName += metadata.artist[0] + ' - '; } if (metadata.title) { fileName += metadata.title; } // append extension fileName += path.extname(source); // join directory and name callback(null, path.join(filePath, fileName)); } // create target directory and move the file function moveFile(source, target, callback) { async.series([ function (asyncCallback) { fse.mkdirs(path.dirname(target), asyncCallback); }, function (asyncCallback) { fse.move(source, target, asyncCallback); } ], function (err, results) { if (err) { return callback(err); } callback(); }); } // fill a string beginning from the front function frontFill(string, fill, length) { while (string.toString().length < length) { string = fill + string; } return string; } // list files in directory function readDirRecursive(where, extension, callback) { if (extension.indexOf('.') !== 0) { extension = '.' + extension; } recursive(where, [ignoreFilter], callback); function ignoreFilter(file, stats) { return !stats.isDirectory() && extension.indexOf(path.extname(file)) === -1; } } // api exports.getPathByMetadata = getPathByMetadata; exports.moveFile = moveFile; exports.frontFill = frontFill; exports.readDirRecursive = readDirRecursive;