Copy to clipboard in Node.js?


Is there a way you can copy to clipboard in Node.js? Any modules or ideas what so ever? I'm using Node.js on a desktop application. Hopefully that clears up why I want it to be able to achieve this.

5/1/2017 7:48:30 AM

Accepted Answer

A clipboard is not inherent to an operating system. It's a construct of whatever window system the operating system happens to be running. So if you wanted this to work on X for example, you would need bindings to Xlib and/or XCB. Xlib bindings for node actually exist: Although I'm not sure whether it gives you access to the X clipboard, you might end up writing your own. You'll need separate bindings for windows.

edit: If you want to do something hacky, you could also use xclip:

var exec = require('child_process').exec;

var getClipboard = function(func) {
  exec('/usr/bin/xclip -o -selection clipboard', function(err, stdout, stderr) {
    if (err || stderr) return func(err || new Error(stderr));
    func(null, stdout);

getClipboard(function(err, text) {
  if (err) throw err;
12/16/2011 9:47:12 AM

For OS X:

function pbcopy(data) {
    var proc = require('child_process').spawn('pbcopy'); 
    proc.stdin.write(data); proc.stdin.end();

write() can take a buffer or a string. The default encoding for a string will be utf-8.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow