Skip to content

Instantly share code, notes, and snippets.

@i-rocky
Created July 15, 2021 05:28
Show Gist options
  • Select an option

  • Save i-rocky/8bffd8513b071abbbff7b3a1a12b285a to your computer and use it in GitHub Desktop.

Select an option

Save i-rocky/8bffd8513b071abbbff7b3a1a12b285a to your computer and use it in GitHub Desktop.
const path = require('path');
const chokidar = require('chokidar');
const SFTPClient = require('ssh2-sftp-client');
const {ChannelQueue} = require('@buttercup/channel-queue');
async function connectSFTP() {
const sftp = new SFTPClient();
return new Promise((resolve, reject) => {
sftp
.connect({
host: '127.0.0.1',
username: 'rocky',
password: 'k',
})
.then(() => resolve(sftp))
.catch(reject);
});
}
function startChokidar(sftp, queue, root, map) {
function getSourceAndDestination(dir, entry) {
const source = path.resolve(__dirname, entry);
const destination = (root + map[dir] + entry.substr(dir.length + 1))
.replace(/\\/g, '/');
return {source, destination};
}
Object.keys(map).forEach(dir => {
chokidar
.watch(dir)
.on('add', (file) => {
queue.enqueue(() => {
const {source, destination} = getSourceAndDestination(dir, file);
console.log('Uploading file', {source, destination});
sftp.put(source, destination);
});
})
.on('addDir', (dirName) => {
queue.enqueue(async () => {
const {destination} = getSourceAndDestination(dir, dirName);
console.log('Adding directory', {destination});
if (!await sftp.exists(destination)) {
sftp.mkdir(destination, true);
}
else {
console.log('[*] Directory exists');
}
});
})
.on('unlink', (file) => {
queue.enqueue(async () => {
const {destination} = getSourceAndDestination(dir, file);
console.log('Deleting file', {destination});
if (await sftp.exists(destination)) {
sftp.delete(destination);
}
});
})
.on('unlinkDir', (dirName) => {
queue.enqueue(async () => {
const {destination} = getSourceAndDestination(dir, dirName);
console.log('Deleting directory', {destination});
if (await sftp.exists(destination)) {
sftp.rmdir(destination, true);
}
});
})
.on('change', (entry, stats) => {
queue.enqueue(() => {
const {source, destination} = getSourceAndDestination(dir, entry);
if (stats.isFile()) {
console.log('Uploading file', {source, destination});
sftp.put(source, destination);
}
else {
console.log('Renaming directory', {source, destination});
}
});
});
});
}
async function start(root, map) {
const sftp = await connectSFTP();
const queue = new ChannelQueue().channel('sync');
startChokidar(sftp, queue, root, map);
}
start('/root/directory/in/the/server',
{
'local/directory': '/directory/relative/to/the/root/',
})
.then(() => {
console.log('Done');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment