import {exec} from 'child_process' import path from 'path' import fs from 'fs-extra' function filewalker (dir, done) { let results = [] fs.readdir(dir, function (err, list) { if (err) return done(err) let pending = list.length if (!pending) return done(null, results) list.forEach(function (file) { file = path.resolve(dir, file) fs.stat(file, function (err, stat) { if (err) return done(err) // If directory, execute a recursive call if (stat && stat.isDirectory()) { filewalker(file, function (err, res) { if (err) return done(err) results = results.concat(res) if (!--pending) done(null, results) }) } else { results.push(file) if (!--pending) done(null, results) } }) }) }) } async function insertDB (db, track) { let ensure = await db.get('SELECT * FROM Track WHERE title=? AND artist=?', track.title, track.artist) if (ensure) { return null } await db.run('INSERT INTO Track VALUES (NULL,?,?,?,?,?,?,?,?)', [track.title, track.artist, track.file, track.album || null, track.genre || null, track.track || null, track.year || null, Math.floor(track.duration)]) return track } function getFiles (dir) { return new Promise((resolve, reject) => { filewalker(dir, (err, files) => { if (err) return reject(err) resolve(files) }) }) } function promiseExec (cmd, opts) { return new Promise((resolve, reject) => { exec(cmd, opts, function (err, stdout, stderr) { if (err) return reject(err) resolve({stdout, stderr}) }) }) } function askAsync (rl, q) { return new Promise((resolve, reject) => { rl.question(q, resolve) }) } export default {getFiles, promiseExec, askAsync, insertDB}