当前位置:   article > 正文

nodejs base64 编码解码

nodejs base64

一、普通字符串

编码

  1. var b = new Buffer('JavaScript');
  2. var s = b.toString('base64');
  3. // SmF2YVNjcmlwdA==

解码:

  1. var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
  2. var s = b.toString();
  3. // JavaScript

二、编码解码并转成hex

  1. var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
  2. var s = b.toString('hex');
  3. // 4a617661536372697074
  1. var b = new Buffer('4a617661536372697074', 'hex')
  2. var s = b.toString('utf8');
  3. // JavaScript

三、编码解码图片

  1. var fs = require('fs');
  2. // function to encode file data to base64 encoded string
  3. function base64_encode(file) {
  4. // read binary data
  5. var bitmap = fs.readFileSync(file);
  6. // convert binary data to base64 encoded string
  7. return new Buffer(bitmap).toString('base64');
  8. }
  9. // function to create file from base64 encoded string
  10. function base64_decode(base64str, file) {
  11. // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
  12. var bitmap = new Buffer(base64str, 'base64');
  13. // write buffer to file
  14. fs.writeFileSync(file, bitmap);
  15. console.log('******** File created from base64 encoded string ********');
  16. }
  17. // convert image to base64 encoded string
  18. var base64str = base64_encode('kitten.jpg');
  19. console.log(base64str);
  20. // convert base64 string back to image
  21. base64_decode(base64str, 'copy.jpg');

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/646884
推荐阅读
相关标签
  

闽ICP备14008679号