节点js中的十六进制到字符串和字符串到十六进制的转换

Hex to String & String to Hex conversion in nodejs

我需要使用 nodejs 8 将数据从字符串转换为十六进制,然后再从十六进制转换为字符串

我在从十六进制解码为字符串时遇到问题

转换代码string into hex

function stringToHex(str)
{
    const buf = Buffer.from(str, 'utf8');
    return buf.toString('hex');
}

转换代码hex into string

function hexToString(str)
{
    const buf = new Buffer(str, 'hex');
    return buf.toString('utf8');
}

我有字符串dailyfile.host

编码的输出:3162316637526b62784a5a37697a45796c656d465643747a4a505a6f59774641534c75714733544b4446553d

解码的输出:1b1f7RkbxJZ7izEylemFVCtzJPZoYwFASLuqG3TKDFU=

需要解码输出:dailyfile.host

您还需要使用 Buffer.from() 进行解码。考虑写一个高阶函数来减少重复代码量:

const convert = (from, to) => str => Buffer.from(str, from).toString(to)
const utf8ToHex = convert('utf8', 'hex')
const hexToUtf8 = convert('hex', 'utf8')

hexToUtf8(utf8ToHex('dailyfile.host')) === 'dailyfile.host'