Search code examples
node.jsclipboard

How to copy multiple values into clipboard in node js?


Title meaning, I have several strings, which I want to be in clipboard, like it would be if I copied them manually. Which also means, if I were to use default Windows Win+V command or Clipdiary - all of strings would appear as different values, as such:
Manual copy = different values

But if you:
Copy via code = they are replacing themselves

P.S. Screenshots of different ways (Clipdiary vs Win+V) to access clipboard were by choice, to show that its not the program fault or Windows.

It doesnt matter, but heres code from pictures, using copy-paste:

const ncp = require(`copy-paste`);

ncp.copy(`But they`);
ncp.copy(`replace one another.`);

So, also I already tried Clipboardy v2.3.0 for CJS compatability and spawning child process from this answer to similar question - all the same:

const cp = require('child_process').spawn('clip');

cp.stdin.write(`yo`);
cp.stdin.write(`hey`);

// and 

cp.stdin.write(`yo`);
cp.stdin.end(`hey`);

// and even spawning new processes

const cp2 = require('child_process').spawn('clip');
cp2.stdin.write(`hey`);
cp2.stdin.end(`yo`);

// and all other possible ways

And all other answers on that question also didnt worked for me. So, here I am questioning my sanity.


Solution

  • Asked ChatGPT and got my answer:

    const copyPaste = require('copy-paste');
    
    const valuesToCopy = [
      'Value 1',
      'Value 2',
      'Value 3',
      // Add more values as needed
    ];
    
    async function copyValuesToClipboard() {
      for (const value of valuesToCopy) {
        copyPaste.copy(value, () => {
          console.log(`Copied: ${value}`);
        });
        await sleep(1000); // Delay for 1 second (adjust as needed)
      }
    }
    
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    copyValuesToClipboard()
      .then(() => {
        console.log('All values copied to clipboard.');
      })
      .catch(err => {
        console.error('Error copying values to clipboard:', err);
      });