Created
February 13, 2019 11:51
-
-
Save agustik/ef1c45d677ed69752609428a9b7df89b to your computer and use it in GitHub Desktop.
Move file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// npm install yargs node-watch | |
// node index.js -s watherfolder -d destfolder | |
const watch = require('node-watch'); | |
const argv = require('yargs').argv; | |
const fs = require('fs'); | |
const util = require('util'); | |
const path = require('path'); | |
const readFile = util.promisify(fs.readFile); | |
const writeFile = util.promisify(fs.writeFile); | |
const stat = util.promisify(fs.stat); | |
const rename = util.promisify(fs.rename); | |
const unlink = util.promisify(fs.unlink); | |
function moveFile(oldPath, newPath) { | |
return new Promise(async function (resolve, reject){ | |
try { | |
await rename(oldPath, newPath); | |
} catch (e) { | |
if (e.code === 'EXDEV'){ | |
try { | |
await copyFile(oldPath, newPath); | |
} catch (e) { | |
return reject(e) | |
} | |
await unlink(oldPath) | |
return resolve(true); | |
}else{ | |
return reject(e); | |
} | |
} | |
return resolve(true); | |
}); | |
} | |
async function isFile(location){ | |
let stats; | |
try { | |
stats = await stat(location); | |
return stats.isFile(); | |
} catch (e) { | |
return false; | |
} | |
} | |
async function isDirectory(location){ | |
let stats; | |
try { | |
stats = await stat(location); | |
return stats.isDirectory(); | |
} catch (e) { | |
return false; | |
} | |
} | |
(async function start(){ | |
const src = (typeof argv.s === 'string') ? argv.s : false; | |
const dst = (typeof argv.d === 'string') ? argv.d : false; | |
if ( ! await isDirectory(src) ) { | |
console.log(`${src} is not a directory`); | |
process.exit(1); | |
} | |
if ( ! await isDirectory(dst) ) { | |
console.log(`${dst} is not a directory`); | |
process.exit(1); | |
} | |
console.log(`Watching ${src} and moving to ${dst}`) | |
watch(src, { recursive: true }, async function(evt, name) { | |
const file = path.relative(src, name); | |
const newPath = path.join(dst, file); | |
console.log({evt, name, file, newPath}); | |
if (evt === 'update'){ | |
console.log(`Move ${name} to ${newPath}`) | |
await moveFile(name, newPath); | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment