|
20 | 20 | // This module defines a cross-platform UTF-8 encoder and decoder that works |
21 | 21 | // with the Buffer API defined in buf.js |
22 | 22 |
|
23 | | -import {alloc, NodeBuffer, HeapBuffer, CombinedBuffer} from "./buf"; |
| 23 | +import {alloc, CombinedBuffer, HeapBuffer, NodeBuffer} from './buf'; |
24 | 24 | import {StringDecoder} from 'string_decoder'; |
25 | 25 | import {newError} from './../error'; |
| 26 | + |
26 | 27 | let platformObj = {}; |
27 | 28 |
|
28 | 29 |
|
29 | 30 | try { |
30 | 31 | // This will throw an exception is 'buffer' is not available |
31 | 32 | require.resolve("buffer"); |
32 | | - let decoder = new StringDecoder('utf8'); |
33 | | - let node = require("buffer"); |
| 33 | + const decoder = new StringDecoder('utf8'); |
| 34 | + const node = require('buffer'); |
| 35 | + |
| 36 | + // use static factory function present in newer NodeJS versions to create a buffer containing the given string |
| 37 | + // or fallback to the old, potentially deprecated constructor |
| 38 | + const newNodeJSBuffer = typeof node.Buffer.from === 'function' |
| 39 | + ? str => node.Buffer.from(str, 'utf8') |
| 40 | + : str => new node.Buffer(str, 'utf8'); |
34 | 41 |
|
35 | 42 | platformObj = { |
36 | 43 | "encode": function (str) { |
37 | | - return new NodeBuffer(new node.Buffer(str, "UTF-8")); |
| 44 | + return new NodeBuffer(newNodeJSBuffer(str)); |
38 | 45 | }, |
39 | 46 | "decode": function (buffer, length) { |
40 | 47 | if (buffer instanceof NodeBuffer) { |
|
0 commit comments