You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
3 years ago
|
"use strict";
|
||
|
|
||
|
const { StringDecoder } = require("string_decoder");
|
||
|
|
||
|
const pipe = require("@promistream/pipe");
|
||
|
const map = require("@promistream/map");
|
||
|
const buffer = require("@promistream/buffer");
|
||
|
const lastWill = require("@promistream/last-will");
|
||
|
|
||
|
const { validateArguments } = require("@validatem/core");
|
||
|
const required = require("@validatem/required");
|
||
|
const ValidationError = require("@validatem/error");
|
||
|
|
||
|
// FIXME: Move into separate @validatem/* package
|
||
|
function isValidTextEncoding(encoding) {
|
||
|
if (!Buffer.isEncoding(encoding)) {
|
||
|
throw new ValidationError(`Must be a valid Buffer text encoding`);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = function decodeString(_encoding) {
|
||
|
let [ encoding ] = validateArguments(arguments, {
|
||
|
encoding: [ required, isValidTextEncoding ]
|
||
|
});
|
||
|
|
||
|
let decoder = new StringDecoder(encoding);
|
||
|
|
||
|
return pipe([
|
||
|
map((inputBuffer) => {
|
||
|
let decoded = decoder.write(inputBuffer);
|
||
|
|
||
|
return (decoded.length > 0)
|
||
|
? [ decoded ]
|
||
|
: [];
|
||
|
}),
|
||
|
buffer(),
|
||
|
lastWill(() => {
|
||
|
let lastChunk = decoder.end();
|
||
|
|
||
|
return (lastChunk.length > 0)
|
||
|
? lastChunk
|
||
|
: lastWill.NoValue;
|
||
|
})
|
||
|
]);
|
||
|
};
|