Skip to content

Instantly share code, notes, and snippets.

@sugyan sugyan/preview.js
Created Jul 22, 2011

Embed
What would you like to do?
realtime markdown preview with Socket.IO
#!/usr/bin/env node
var fs = require('fs');
var http = require('http');
var md = require('markdown');
var target = process.argv[2];
if (! target) {
console.error('usage: ' + process.argv.join(' ') + ' <filename>');
process.exit(1);
}
var server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(
'<!DOCTYPE html><html><head><script type="text/javascript" src="/socket.io/socket.io.js"></script>' +
'<script type="text/javascript">var socket = io.connect();socket.on("change", function (html) { document.getElementById("preview").innerHTML = html; });</script>' +
'</head><body><div id="preview"></div></body></html>'
);
});
server.listen(3000);
var io = require('socket.io').listen(server);
fs.stat(target, function (err, stat) {
if (err) { throw err; }
if(! stat.isFile()) {
console.error(target + ' is not file');
process.exit(1);
}
fs.watchFile(target, { interval: 500 }, function (curr, prev) {
fs.readFile(target, 'utf8', function (err, text) {
if (err) { throw err; }
io.sockets.emit('change', md.parse(text));
});
});
});
#!/usr/bin/env plackup
use strict;
use warnings;
use Encode 'decode_utf8';
use Plack::Builder;
use PocketIO;
use Path::Class 'file';
use Amon2::Lite;
use Filesys::Notify::Simple;
use Text::Markdown 'markdown';
shift; # psgi
my $target = shift or die;
-f $target or die;
$target = file($target);
get '/' => sub {
my ($c) = @_;
return $c->render('index.tt');
};
builder {
mount '/socket.io' => PocketIO->new(
handler => sub {
my $self = shift;
my $watcher = Filesys::Notify::Simple->new(['.']);
while (1) {
$watcher->wait(
sub {
my @events = @_;
for my $event (@events) {
next if $event->{path} ne $target->absolute;
my $text = $target->slurp;
$self->send_message({
html => decode_utf8(markdown($text)),
});
}
},
);
}
},
);
mount '/' => __PACKAGE__->to_app;
};
__DATA__
@@ index.tt
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>preview</title>
<script type="text/javascript" src="https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
socket.on('message', function (msg) {
document.getElementById('preview').innerHTML = msg.html
});
</script>
</head>
<body>
<div id="preview"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.