最近在做一个项目需求是读取计算机名称
在windows上使用nodejs exec读取时会有些电脑上会出现乱码问题
直接在cmd上执行hostname,返回的是没有问题的
当我使用exec读取时就乱码了,虽然可以使用iconv进行转码,但是不同电脑的活动代码页是不一样的,就需要在获取后根据chcp值做对应的转码。
常见的chcp:
获取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)
})
})
分享一下mac的:
macOS活动电脑名称ComputerName 命令:
exec('scutil --get ComputerName', { encoding: 'utf-8' }, function (err, stdout, stderr) {
if (err) {
console.error(err)
}
console.log("ComputerName: ", stdout)
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)