How can I input the correct encoding to pbcopy in node.js?

309 views Asked by At
const proc = require('child_process').spawn('pbcopy');
const iconv = require('iconv-lite');
const name = '吉星高照';

function iconvDecode(str = '') {
  return iconv.decode(Buffer.from(str, 'binary'), 'cp936');
}

function pbcopy(data) {
  proc.stdin.write(iconvDecode(data));
  proc.stdin.end();
  return data;
}

pbcopy(name);

The expected output from the clipboard (on macOS) should be 吉星高照 but instead it is ˱®.

1

There are 1 answers

0
Aero Wang On BEST ANSWER

Turns out I need to set the environment variable LC_CTYPE for pbcopy:

const proc = require('child_process').spawn('pbcopy', {
  env: {
    LC_CTYPE: 'UTF-8',
  },
});
const name = '吉星高照';

function pbcopy(data) {
  proc.stdin.write(data);
  proc.stdin.end();
  return data;
}

pbcopy(name);