如何在 node.js 中输入正确的编码到 pbcopy?

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

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);

剪贴板(在 macOS 上)的预期输出应该是 吉星高照,但实际上是 ˱®

原来我需要为 pbcopy 设置环境变量 LC_CTYPE:

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);