Skip to content

Instantly share code, notes, and snippets.

@mkremins
Created April 17, 2014 21:41
Show Gist options
  • Save mkremins/11013151 to your computer and use it in GitHub Desktop.
Save mkremins/11013151 to your computer and use it in GitHub Desktop.
node.js: put text into OS X clipboard
function pbcopy(data) {
var proc = require('child_process').spawn('pbcopy');
proc.stdin.write(data);
proc.stdin.end();
}
@flrngel
Copy link

flrngel commented May 2, 2017

awesome

@lasergoat
Copy link

lasergoat commented Jun 16, 2017

Awesome! I took it a step further if anyone needs one that can handle errors too:

function pbcopy(data) {
  return new Promise(function(resolve, reject) {
    const proc = require('child_process').spawn('pbcopy');
    proc.on('error', function(err) {
      reject(err);
    });
    proc.on('close', function(err) {
      resolve();
    });
    proc.stdin.write(data);
    proc.stdin.end();
  })
}

use:

const str = 'bartle';

pbcopy(str).then(function() {
  console.log(`Copied ${str} to clipboard!`);
}).catch(function(e) {
  console.error(new Error(`Could Not Copy ${str} To Clipboard!`));
})

This is good if you don't know which system it will be running on.

@rainb3rry
Copy link

Awesome! I took it a step further if anyone needs one that can handle errors too:

function pbcopy(data) {
  return new Promise(function(resolve, reject) {
    const proc = require('child_process').spawn('pbcopy');
    proc.on('error', function(err) {
      reject(err);
    });
    proc.on('close', function(err) {
      resolve();
    });
    proc.stdin.write(data);
    proc.stdin.end();
  })
}

use:

const str = 'bartle';

pbcopy(str).then(function() {
  console.log(`Copied ${str} to clipboard!`);
}).catch(function(e) {
  console.error(new Error(`Could Not Copy ${str} To Clipboard!`));
})

This is good if you don't know which system it will be running on.

Thanks mate saved my day

@SlideeScherz
Copy link

windows

Basic demo, but should be ~promisified

function clipboardTransport(data) {
  let clipCommand = process.platform === 'win32' ? 'clip' : 'pbcopy';

  const proc = spawn(clipCommand);
  proc.on('close', () => console.log('Copied to clipboard'));
  proc.on('error', console.error);

  proc.stdin.write(data);
  proc.stdin.end();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment