string.js 704 B

1234567891011121314151617181920212223242526272829
  1. 'use strict';
  2. const Iconv = require('iconv-lite');
  3. exports.decode = function(buffer, encoding, options) {
  4. if (Buffer.isEncoding(encoding)) {
  5. return buffer.toString(encoding);
  6. }
  7. const decoder = Iconv.getDecoder(encoding, options || {});
  8. const res = decoder.write(buffer);
  9. const trail = decoder.end();
  10. return trail ? res + trail : res;
  11. };
  12. exports.encode = function(string, encoding, options) {
  13. if (Buffer.isEncoding(encoding)) {
  14. return Buffer.from(string, encoding);
  15. }
  16. const encoder = Iconv.getEncoder(encoding, options || {});
  17. const res = encoder.write(string);
  18. const trail = encoder.end();
  19. return trail && trail.length > 0 ? Buffer.concat([res, trail]) : res;
  20. };