Node.js: tipi comuni di codifica delle stringhe

Node.js: tipi comuni di codifica delle stringhe

In questo articolo illustreremo i tre tipi più comuni di codifica delle stringhe in Node.js.

Base64

Possiamo usare la seguente soluzione:


'use strict';

const Base64 = {
    encode: (str) => {
        return Buffer.from(str, 'utf8').toString('base64');
    },
    decode: (str) => {
        return Buffer.from(str, 'base64').toString('utf8');
    }
};

module.exports = Base64;

MD5

La soluzione è la seguente:


'use strict';

const crypto = require('crypto');

const md5 = (value) => {
    if(!value) {
        return;
    }
    return crypto.createHash('md5').update(value).digest('hex');
    
};

module.exports = md5;

SHA256

La soluzione è la seguente:


'use strict';

const crypto = require('crypto');

const sha256 = (value) => {
    if(!value) {
        return;
    }
    return crypto.createHash('sha256').update(value).digest('hex');
    
};

module.exports = sha256;

Torna su