convert buffer from database to string - node.js
I stored an buffer in database.
I have an buffer like this (from database):
{
data = (
76,
39,
65,
77,
66,
65,
83,
83,
65,
68,
79,
82
);
type = Buffer;
}
I'd like to convert it to string, but it is not working.
I tried with .toString('utf8');
console.log(buffer.toString('utf8');
I get :
{"type":"Buffer","data":[123,10,32,32,32,32,100,97,116,97,32,61,32,32,32,32,32,40,10,32,32,32,32,32,32,32,32,55,54,44,10,32,32,32,32,32,32,32,32,51,57,44,10,32,32,32,32,32,32,32,32,54,53,44,10,32,32,32,32,32,32,32,32,55,55,44,10,32,32,32,32,32,32,32,32,54,54,44,10,32,32,32,32,32,32,32,32,54,53,44,10,32,32,32,32,32,32,32,32,56,51,44,10,32,32,32,32,32,32,32,32,56,51,44,10,32,32,32,32,32,32,32,32,54,53,44,10,32,32,32,32,32,32,32,32,54,56,44,10,32,32,32,32,32,32,32,32,55,57,44,10,32,32,32,32,32,32,32,32,56,50,10,32,32,32,32,41,59,10,32,32,32,32,116,121,112,101,32,61,32,66,117,102,102,101,114,59,10,125]}
What's wrong in this? How can I get the value of this buffer?
Use the Buffer.from(array) syntax.
const data = [76,39,65,77,66,65,83,83,65,68,79,82];
const buf = Buffer.from(data)
const str = buf.toString();
console.log('str',str); // outputs L'AMBASSADOR
Related
Mongoose handle base64/ binary encode and decode
I'm struggling to wrap my head around this and I've read all the posts I can find on it, but still am not making sense of the results I'm getting. I'm using react-signature-canvas which produces the output into a base64 string. I then seem to be successfully saving this through Mongoose with: let data = req.body.submittedSig.data; let split = data.split(','); let base64string = split[1]; const buffer = Buffer.from(base64string, 'base64'); //...// submittedSig: { data: buffer, contentType: plan.submittedSig.contentType }, this shows in the db as: submittedSig Object data BinData(0, 'iVBORw0KGgoAAAANSUhEUgAAAJYAAABsCAYAAACICEudAAANIElEQVR4Xu2dSwgsRxWGjaj4CKjgxpVzjYrowidowOAoxMcmKgqi…') contentType "image/png" When trying to decode, I've used several approaches such as .toBase64() - https://www.mongodb.com/docs/atlas/app-services/functions/globals/#bson--binary-json- mongo function, but I get a 'not a function' error, and otherwise I've played with various combinations of Buffer.from(data, 'base64') and .toString('base64'). https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding const servicePlan = await ServicePlan.findOne({ _id: req.params.planId }) // let sig = Buffer.from(servicePlan.submittedSig.data, 'base64').toString('base64'); // sig = servicePlan.submittedSig.data.toString('base64'); sig = servicePlan.submittedSig.data.toBase64(); servicePlan.submittedSig.data = sig console.log("sig plan: ", servicePlan) res.send(servicePlan) For any combination of the Buffer.from or .toString- whether used separetely or together, the console.logs the output as data: new Binary(Buffer.from("6956424f5277304b ... 414141456c46546b5375516d4343", "hex"), 0), and the return comes as: "submittedSig": { "data": { "type": "Buffer", "data": [ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, ... ] So as far as I can tell, the encoding takes it into binary, but all of my output is not decoding back to base64. Let alone, the end of the console.log of shows 'hex' which had me trying to convert the binary as if it was stored as a hex object, but that hasn't worked either. I'm sure its something simple that I just don't get with these, appreciate any guidance.
How to center continued text using PdfKit?
I have this code: const PDFDocument = require("pdfkit"); const QRCode = require("qrcode"); const fs = require("fs"); const exec = async () => { const doc = new PDFDocument({ layout: "landscape" }); doc.pipe(fs.createWriteStream("output.pdf")); for (let pageNumber = 1; pageNumber <= 1000; pageNumber++) { const url = await QRCode.toDataURL("I am a url!"); doc .image(url, 10, 100, { width: 420, height: 420, align: "center", valign: "center", }) doc .font("Helvetica") .fontSize(50) .fillColor("#000") .text(`Item `, 465, 200, { continued: true }) .fontSize(55) .font("Courier-Bold") .fillColor("#1b83c5") .text(`${pageNumber}`); doc .font("Helvetica-Bold") .fontSize(40) .fillColor("#000") .text("Order and Pay", 420, 320); doc.addPage(); } doc.end(); }; exec(); Which would produce something like this: It looks centered and all, but as pages increase it will no longer be centered since the numbers are fixed. I saw in the docs that there's an align property, but the docs didn't explain how to handle continued text. Any working examples?
Maybe it's a little late, but I found a solution battling with the same problem: First you need to create a constant with the width of the container you want to center your text in: (this value you have to calculate or invent, but it's easy to do that) const containerWidth = 100 // as an example Then, you need to create a variable that contains a plain string that contains all the text you want to center, in your example: var appendedText = `Item ${pageNumber}` To finish, you need to use pdf-kit's function: widthOfString, and add the text in the document as follows: const xOffset = 465 // The original X offset value doc .text(`Item `, xOffset + (containerWidth / 2) - (doc.widthOfString(appendedText) / 2), 200, { continued: true }) .text(`${pageNumber}`); Removed the text styling lines for clarity, but you have to add them later.
Clap raw bytes arguments
I would like to use raw byte argument with clap For example --raw $(echo -n -e 'B\x10CC\x01\xff') will give me the following bytes array [66, 16, 67, 67, 1, 239, 191, 189] (using to_string_lossy().to_bytes()). Is there a way to get exact bytes array using clap? EDIT let cmd = Command::new( env!("CARGO_CRATE_NAME") ).bin_name( env!("CARGO_CRATE_NAME") ).arg( Arg::new("raw").long("raw").takes_value(true).allow_invalid_utf8(true) ); let matches = cmd.get_matches(); match matches.value_of_os("raw") { Some(s) => { match s.to_str() { Some(s3) => { let v2: &[u8] = s3.as_bytes(); println!("OsStr(bytes):{:?}", v2); }, None => {}, } let s2 = s.to_string_lossy(); println!("string_from_OsString:{}", s2); let v3: &[u8] = s2.as_bytes(); println!("OsString.to_lossy(bytes):{:?}", v3); }, None => {}, } return for input --raw $(echo -n -e 'B\x10CC\x01\xff') string_from_OsString:BCC� OsString.to_lossy(bytes):[66, 16, 67, 67, 1, 239, 191, 189] Thank you
clap is platform agnostic and therefore uses abstractions like OsString (which is the type of your s variable). There seems to be no generic as_bytes() method attached to OsString, because not on every operating system OsString is actually a raw bytes array. Here is a lot more discussion about this very topic: How can I convert OsStr to &[u8]/Vec<u8> on Windows? So to solve your problem, it seems necessary that you narrow your compatibility down to a specific operating system. In your case, it seems that you are using Unix. Which is great, because for Unix, such a method does exist! Here you go: use clap::{Arg, Command}; use std::os::unix::ffi::OsStrExt; fn main() { let cmd = Command::new(env!("CARGO_CRATE_NAME")) .bin_name(env!("CARGO_CRATE_NAME")) .arg( Arg::new("raw") .long("raw") .takes_value(true) .allow_invalid_utf8(true), ); let matches = cmd.get_matches(); match matches.value_of_os("raw") { Some(s) => { println!(".as_bytes(): {:?}", s.as_bytes()); } None => {} } } .as_bytes(): [66, 16, 67, 67, 1, 255] Note that the use std::os::unix::ffi::OsStrExt; will add the .as_bytes() functionality to OsString, but will fail to compile on non-unix systems.
Can not get Group to show up when menu item is selected
I have been trying to get menu and submenu items to produce the output desired. I have tried multiple ways and some work part way and other do not work at all. Below is my latest try. The main window shows up and the menu and submenu items can be selected. I have println! statements in each one and the results show up on the terminal window when selected. What is not happening is the GROUP is not displaying although I know I am in the area because I get the output from the two println!'s. What in the world am I doing wrong????? For those that think I should be learning how to do this myself please point me to some info that I can read to help me solve this problem. All the information I have found so has all the items in a single thread with no branching. main_win.show(); main_win.set_callback(move|_| { if app::event() == Event::Close { s.send(Message::Quit); } }); while app.wait() { use Message::*; if let Some(msg) = r.recv() { match msg { Preference => { println!("In Preference area"); } Quit => { app.quit(); } Wallets => { println!("In Wallets area"); let mut wall_group = fltk::group::Group::new(50, 90, 500, 300, "Wallet Data Add/Change/Delete"); wall_group.set_frame(FrameType::FlatBox); wall_group.set_color(Color::by_index(2)); wall_group.end(); let wall_name = fltk::input::Input::new(180, 105, 170, 20, "Wallet Name:"); wall_group.add(&wall_name); let wall_username = fltk::input::Input::new(180, 130, 170, 20, "Wallet Username:"); wall_group.add(&wall_username); let wall_password = fltk::input::Input::new(180, 155, 170, 20, "Wallet Password:"); wall_group.add(&wall_password); let btn_wall_add = fltk::button::Button::new(180, 190, 60, 20, "Add"); wall_group.add(&btn_wall_add); let btn_wall_delete = fltk::button::Button::new(260, 190, 60, 20, "Delete"); wall_group.add(&btn_wall_delete); println!("In Wallets area 2"); }
Currently the instantiated group isn’t parented directly or indirectly to the window. You can use window.add(&wall_group) to add it (or use insert). Better yet, you can already create the group, keep it hidden, then call show in the Wallets event.
library cbor introduces a new value in the conversion
I made on node.js, this program, which has an anomaly. When I do decodeAllSync I get a vector of decimal numbers which has one fewer numbers than I get by reconverting the vector with encodeAsync. Why don't I get the same vector? Thank you const cbor = require('cbor'); ... const results = cbor.decodeAllSync(output); const input = cbor.encodeAsync(results); console.log(output); input.then( function (x) { var v=new Uint8Array(x); console.log(v); }, function () { console.log("fail "); }); I receive for the printout of the input: Uint8Array [ 129, 210, 132, 77, ... I receive for the printout of the output: Uint8Array [ 210, 132, 77, ...
cbor.decodeAllSync with n arguments returns an array with n entries. So what you encode has an extra pair of [] around it. > cbor.decodeAllSync(cbor.encode(1)) [ 1 ] > cbor.decode(cbor.encode(1)) 1