Node Buffer 1 – Encoding & Decoding

Buffer 学习第一部分,编解码。

场景 1,Basic Authentication

Schema:Authorization: <type> <credentials>

;(function() {
  'use strict';

  // eg. 1. Basic authentication
  const user = 'johnny';
  const pass = 'c-bad';
  const authstring = `${user}:${pass}`;
  
  // encode
  const buf = Buffer.from(authstring);
  const encoded = buf.toString('base64');
  
  console.log({encoded});
  
  // decode
  const buf1 = Buffer.from(encoded, 'base64');
  const decoded = buf1.toString();
  
  console.log({decoded});
}());

场景 2,Base64 Images

Schema:data:[<media type>][;base64],<data>

;(function() {
  'use strict';

  const fs = require('fs');

  const mime = 'image/png';
  const encoding = 'base64';

  // encode
  const data = fs.readFileSync('./fruit.png').toString(encoding);
  const uri = `data:${mime};${encoding},${data}`;

  console.log(uri);

  // decode
  const data1 = uri.split(',')[1];
  const buf = Buffer.from(data1, 'base64');
  fs.writeFileSync('./fruit1.png', buf);
}());

参考:

  1. Alex Young, Marc Harter. Node in Practice. 2015
  2. https://en.wikipedia.org/wiki/Data_URI_scheme
  3. https://www.lemoda.net/c/write-png/

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s