There is a requirement to implement node.js replication function on Windows platform. There are some problems in the implementation process.

First of all, this requirement is obviously small, and I’m going to implement it myself without thinking about cross-platform. Node.js itself does not have a similar function, while CMD should have a similar implementation:

echo biebuxin | clip
Copy the code

Node.js code can be written like this:

const { exec } = require('child_process');

exec('echo biebuxin | clip');
Copy the code

The expected result is that the string biebuxin is copied to the clipboard. After pasting, I found that I copied more than biebuxin, followed by a space and a newline.

What if I don’t want extra space and line breaks? Another way to write it is:

exec('clip').stdin.end('biebuxin');
Copy the code

This paste, no more, no less, is biebuxin.

Did you think it was over? Naive…

When you want to copy Chinese, for example:

exec('clip').stdin.end('Don't believe it.');
Copy the code

Paste it out, you’ll find it’s garbled!

Why is it garbled?

It’s the coding.

Executing CHCP in CMD results in “Active code page: 936”. This indicates that CMD is GBK encoded by default. By default, Node.js uses UTF-8 encoding – a difference that can cause problems for Chinese.

Then I tried to change the encoding to GBK, only to find that Node.js does not support GBK encoding.

At this time, have to use iconV-Lite this powerful coding conversion tool, the code is as follows:

const { exec } = require('child_process');
const iconv = require('iconv-lite');

exec('clip').stdin.end(iconv.encode('Don't believe it.'.'gbk'));
Copy the code

Paste it. Perfect.

Personal technology blog Biebu.xin, original link – The Windows platform Node.js implementation copies any text to the clipboard