Search code examples
javascriptnode.jsclipboard

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.


Solution

  • 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: https://github.com/mixu/nwm. 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;
      console.log(text);
    });