Recently I am working on a project that needs to read the computer name.
When using nodejs exec on windows to read, there will be garbled characters on some computers.
Execute hostname directly on cmd, and the return is no problem.
When I use exec to read, it is garbled. Although iconv can be used to transcode, the active code page of different computers is different, so it needs to be obtained according to The chcp value performs corresponding transcoding.
Common chcps:
Code to get hostname:
const CODE_PAGE = {
'936': 'gbk',
'65001': 'utf-8'
};
exec('chcp', function (_err, _stdout, _stderr) {
if (_err) {
console.error(_err)
}
const page = _stdout.replace(/[^0-9]/ig, "");
let _encoding = CODE_PAGE[page]
exec('hostname', {
encoding: 'buffer' }, function (err, stdout, stderr) {
if (err) {
console.error(err)
}
const _de = iconv.decode(stdout, _encoding)
const hostname = iconv.encode(_de, 'utf-8').toString().trim() || ''
console.log("hostname: ", hostname)
})
})
Share the mac:
macOS active computer name ComputerName command:
exec('scutil --get ComputerName', {
encoding: 'utf-8' }, function (err, stdout, stderr) {
if (err) {
console.error(err)
}
console.log("ComputerName: ", stdout)
})