r/ScriptSwap • u/null_undefined • Jun 07 '14
[Javascript[NodeJS]] Share your clipboard with friends and strangers
Whenever I use SSH, I often get frustrated because I often want to share the clipboard between my computer and remote computer. So I wrote this tiny JS script that works as follows and can be run with node.
GET requests return the content of the clipboard in the response body POST requests copy the request body to the clipboard
The code is as follows:
var spawn = require('child_process').spawn;
var http = require('http');
function handleRequest(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
if (body.length > 1e6)
req.connection.destroy();
});
request.on('end', function () {
var pbcopy = spawn('pbcopy');
pbcopy.stdin.write(body); pbcopy.stdin.end();
var notify = spawn('terminal-notifier', ['-message', 'A message has been copied to your clipboard.']);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(body);
});
} else {
var content = '';
var pbpaste = spawn('pbpaste');
pbpaste.stdout.on('data', function(data){
content += data;
});
pbpaste.stdout.on('end', function(){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(content);
});
}
}
http.createServer(handleRequest).listen(1337);
To copy:
curl {your-ip}:1337
To paste from standard input:
curl -XPOST {your-ip}:1337 --data-binary @-
If you alias the above commands as scripts zcopy and zpaste respectively, then they will function almost exactly like pbcopy and pbpaste.
Also, note that this is only possible if the remote computer can connect to your computer directly as well, so it will not work if you are behind a firewall (although I think you could do remote ssh port forwarding to accomplish this).
This script only works on Mac OS X because it uses pbcopy and pbpaste, but could easily be modified to work with other clipboard systems. And it also uses the terminal-notifier application to send notifications when something is placed on your clipboard. This is available here: https://github.com/alloy/terminal-notifier
Also, if anyone knows of a better way to do clipboard sharing, let me know! I was thinking there may be a better solution, but I was not certain.
View all comments
Show parent comment
1
u/emergent_properties Jun 25 '14
Just make a disclaimer that this is as safe as the Telnet server + clipboard access, and we're all good.
Real uses of this will be (hopefully) behind SSL certs and proxies and all that jazz...