Skip to content

Commit

Permalink
feat: add toString
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbonnet committed May 30, 2022
1 parent 438f4b1 commit 9e7e2d8
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/toString.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Buffer } from "buffer";

import { isString } from "lodash-es";

import { isStream } from "./isStream.js";

const { isBuffer } = Buffer;

export async function toString(value, charset = "utf8") {
if (isString(value)) {
return value;
}
if (isBuffer(value)) {
return value.toString(charset);
}
if (isStream(value)) {
const bufferList = [];
return new Promise((resolve, reject) => {
value
.on("data", (data) => bufferList.push(Buffer.from(data)))
.on("error", (error) => reject(error))
.on("end", () => resolve(Buffer.concat(bufferList).toString(charset)));
});
}
}

0 comments on commit 9e7e2d8

Please sign in to comment.