Node.js Buffer.from All In One
Node.js Buffer.from All In One
Buffer
Buffer.from
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
https://nodejs.org/api/buffer.html#static-method-bufferfrombuffer
toString('base64')
buffer.atob(data)
Legacy. Use Buffer.from(data, 'base64')
instead. ✅
buffer.btoa(data)
Legacy. Use buf.toString('base64')
instead. ✅
https://nodejs.org/api/buffer.html#nodebuffer-module-apis
const convertImageToBase64URL = (filename, imageType = 'png') => {
try {
const buffer = fs.readFileSync(filename);
// ❌ 二合一 Buffer.from(buffer, 'base64')
const base64String = Buffer.from(buffer, 'base64');
// console.log(`base64String`, base64String.slice(0, 100));
return `data:image/${imageType};base64,${base64String}`;
} catch (error) {
throw new Error(`file ${filename} no exist ❌`)
}
}
const convertImageToBase64URL = (filename, imageType = 'png') => {
try {
const buffer = fs.readFileSync(filename);
// ✅ Buffer.from(buffer') + buffer.toString('base64');
const base64String = Buffer.from(buffer).toString('base64');
// console.log(`base64String`, base64String.slice(0, 100));
return `data:image/${imageType};base64,${base64String}`;
} catch (error) {
throw new Error(`file ${filename} no exist ❌`)
}
}
convertImageToBase64URL
Buffer.from
ES6
version
import fs from 'node:fs';
const convertImageToBase64URL = (filename, imageType = 'png') => {
try {
const buffer = fs.readFileSync(filename);
const base64String = Buffer.from(buffer).toString('base64');
// console.log(`base64String`, base64String.slice(0, 100));
return `data:image/${imageType};base64,${base64String}`;
} catch (error) {
throw new Error(`file ${filename} no exist ❌`)
}
}
export {
convertImageToBase64URL,
};
// test cases
const ok = convertImageToBase64URL("./public/test.png");
const err = convertImageToBase64URL();
TypeScript
version
import fs from 'node:fs';
type Filename = string;
type ImageType = 'png' | 'jpg' | 'jpeg' | 'gif' | 'webp';
type Base64String = `data:image/${ImageType};base64,${string}`;
const convertImageToBase64URL = (filename: Filename, imageType: ImageType = 'png'): Base64String => {
try {
const buffer = fs.readFileSync(filename);
const base64String = Buffer.from(buffer).toString('base64');
// console.log(`base64String`, base64String.slice(0, 100));
return `data:image/${imageType};base64,${base64String}`;
} catch (error) {
throw new Error(`file ${filename} no exist ❌`)
}
}
export {
convertImageToBase64URL,
};
// test cases
const ok = convertImageToBase64URL("./public/test.png");
const err = convertImageToBase64URL();
/*
Expected 1-2 arguments, but got 0.ts(2554)
An argument for 'filename' was not provided.
const convertImageToBase64URL: (filename: Filename, imageType?: ImageType) => Base64String
*/
- fs.readFileSync
{encoding: 'base64'}
const convertImageToBase64URL = (filename, imageType = 'png') => {
try {
const base64String = fs.readFileSync(filename, {
encoding: 'base64',
});
console.log(`base64String`, base64String.slice(0, 100));
return `data:image/${imageType};base64,${base64String}`;
} catch (error) {
throw new Error(`file ${filename} no exist ❌`)
}
}
new Buffer
deprecated ⚠️
@deprecated — since v10.0.0 - Use Buffer.from(array) instead.
function base64_encode(file) {
// read binary data
var img = fs.readFileSync(file);
console.log(`img`, img);
// convert binary data to base64 encoded string
return new Buffer(img).toString('base64');
}
/*
The signature '(array: Uint8Array): Buffer' of 'Buffer' is deprecated.ts(6387)
buffer.d.ts(265, 16): The declaration was marked as deprecated here.
var Buffer: BufferConstructor
new (array: Uint8Array) => Buffer (+5 overloads)
Allocates a new buffer containing the given {array} of octets.
@param array — The octets to store.
@deprecated — since v10.0.0 - Use Buffer.from(array) instead.
*/
demos
const fs = require("fs");
var path = require("path");
const { exit } = require("process");
// axios
const axios = require("axios");
const log = console.log;
var folder = path.resolve(__dirname, '../pdf');
// log('folder', folder);
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
async function downloadPDF(url, filename) {
log('🚧 pdf downloading ...');
axios({
method: 'get',
url,
responseType: 'arraybuffer',
// responseType: 'stream',
// responseType: 'document',
})
.then((response) => {
console.log(`response`, response.data);
// response <Buffer 25 50 44 46 2d 31 2e 34 0d 25 e2 e3 cf d3 0d 0a 35 35 20 30 20 6f 62 6a 0d 3c 3c 2f 4c 69 6e 65 61 72 69 7a 65 64 20 31 2f 4c 20 37 35 31 33 32 37 2f ... 751277 more bytes>
// ✅
let pdfBuffer = response.data;
// ✅ 多此一举呀
// let pdfBuffer = Buffer.from(response.data, 'binary');
fs.writeFileSync(filename, pdfBuffer);
log('✅ pdf finished!');
});
}
const url = 'https://cs193p.sites.stanford.edu/sites/g/files/sbiybj16636/files/media/file/l1.pdf';
const filename = folder + '/cs193p-2021-l1.pdf';
log('filename =', filename);
downloadPDF(url, filename);
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
Base64
TextEncoder
&TextDecoder
function base64ToBytes(base64) {
const binString = atob(base64);
return Uint8Array.from(binString, (m) => m.codePointAt(0));
}
function bytesToBase64(bytes) {
const binString = String.fromCodePoint(...bytes);
return btoa(binString);
}
// Usage
bytesToBase64(new TextEncoder().encode("a Ā 𐀀 文 🦄"));
// "YSDEgCDwkICAIOaWhyDwn6aE"
new TextDecoder().decode(base64ToBytes("YSDEgCDwkICAIOaWhyDwn6aE"));
// "a Ā 𐀀 文 🦄"
https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder
https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
Converting arbitrary
binary data
async function bytesToBase64DataUrl(bytes, type = "application/octet-stream") {
return await new Promise((resolve, reject) => {
const reader = Object.assign(new FileReader(), {
onload: () => resolve(reader.result),
onerror: () => reject(reader.error),
});
reader.readAsDataURL(new File([bytes], "", { type }));
});
}
async function dataUrlToBytes(dataUrl) {
const res = await fetch(dataUrl);
return new Uint8Array(await res.arrayBuffer());
}
// Usage
await bytesToBase64DataUrl(new Uint8Array([0, 1, 2]));
// "data:application/octet-stream;base64,AAEC"
await dataUrlToBytes("data:application/octet-stream;base64,AAEC");
// Uint8Array [0, 1, 2]
https://developer.mozilla.org/en-US/docs/Glossary/Base64
ArrayBuffer
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
refs
/Users/xgqfrms-mm/Documents/github/node-web-framework-all-in-one/000-xyz/express-sse/src/convert-image-tobase64-url.ts
https://github.com/xgqfrms/node-web-framework-all-in-one
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17357737.html
未经授权禁止转载,违者必究!