'Listening to Mac pbcopy events in node

On Mac OS using Node, I would like to:

  1. Copy a code snippet from Stack Overflow e.g. console.log('hello world')
  2. Access code snippet console.log('hello world') in running Node program

This is how I imagined it would work

var child_process = require('child_process');
var child = child_process.spawn('pbcopy');

child.stdin.on('data', function (data) {
    // runs every time I copy something to my clipboard
    console.log('data' + data);
});

This doesn't work. Nor does 'readable' event.

I have seen this example to write to the clipboard using pbcopy https://stackoverflow.com/a/13735363/3893510

Thanks for your help

Edit: I have a very crude way to do it using node copy-paste and a timeout

var ncp = require("copy-paste");

const listOfCopiedItems = []
function trackAllCopiedText (prev = "") {
    const text  = ncp.paste()
    if (prev !== text){
        listOfCopiedItems.push({
            text,
            dateTime: new Date()
        })
    }
    setTimeout(() => {
        trackAllCopiedText(text)
    }, 1000);
}
trackAllCopiedText()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source