fs-broadcaster
v0.0.8
Published
Broadcasts file system events via a websocket server
Downloads
3
Readme
fs-broadcaster
A websocket server that broadcasts file system events. Can be run from the commandline.
Installation
# to use as cli
npm install -g fs-broadcaster
# to use as module
npm install --save fs-broadcaster
Usage
Cli
Usage: cli [options]
Starts a websocket server and broadcasts fs events in a given directory
Options:
-h, --help output usage information
-V, --version output the version number
-d, --dir <path> Specify which directory to watch, can recieve a file glob. Defaults to current directory.
-p, --port Port that will be used. Defaults to 1992
Module
import { join } from 'path';
import { BroadCaster } from 'fs-broadcaster';
// Create new broadcaster and pass in the files to watch and port
let broadcaster = new BroadCaster(join(__dirname, '/lib/*.js'), 8080);
// Start socket server and begin to broadcast fs events
broadcaster.startSocketServer();
// List all watched files
broadcaster.listAllWatchedFiles();
// Destroy socket server and remove fs listeners
broadcaster.closeSocketServer();
// Get chokidar instance
broadcaster.getWatcher();
Example
Output
The following will be broadcast to all connected clients when an fs event occurs.
{
event: 'change',
path: 'lib/styles/main.css',
ext: '.css',
stamp: '2017-02-27T21:18:25.929Z'
}
Live reloading on client
A live reloading example using the browser's websocket api and the output from fs-broadcaster.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
function reloadStyles() {
var i, a, s;
a = document.getElementsByTagName('link')
for (i = 0; i < a.length; i++) {
s = a[i]
if (s.rel.toLowerCase().indexOf('stylesheet') >= 0 && s.href) {
var h = s.href.replace(/(&|\?)forceReload=\d+/, '')
s.href = h + (h.indexOf('?') >= 0 ? '&' : '?') + 'forceReload=' + (new Date().valueOf())
}
}
}
var ws = new WebSocket('ws://0.0.0.0:1992')
ws.onmessage = function (msg) {
var data = JSON.parse(msg.data)
if (data.ext === '.html' || data.ext === '.js') {
location.reload()
}
if (data.ext === '.css') {
reloadStyles()
}
}
console.log('==================================')
console.log('Server running in development mode')
console.log('==================================')
</script>
</head>
<body>
<!-- your app -->
</body>
</html>