Guide to converting strings to base64 and vice versa in a TypeScript Express server

Currently, I am using an express server that is written in typescript.

While atob() and btoa() function well within browsers, they do not work on Nodejs environment.

Typically, we rely on

Buffer.from("some-string").toString('base64')
method to encode strings into base64 format.

Unfortunately, when I attempt to implement this in TypeScript, it does not seem to be functioning properly. Any guidance on resolving this issue would be greatly appreciated.

Answer №1

When working with Node.js and TypeScript:

import { Buffer } from "buffer";

const base64String = "SGVsbG8sIFdvcmxkIQ==";
const textString = 'Hello, World!'

const decodeBase64 = (str: string):string => Buffer.from(str, 'base64').toString('binary');
const encodeBase64 = (str: string):string => Buffer.from(str, 'binary').toString('base64');

test('Base64 decoding', () => {
  expect(decodeBase64(base64String)).toEqual(textString)
});

test('Base64 encoding', () => {
  expect(encodeBase64(textString)).toEqual(base64String)
});

test('Base64 encoding/decoding', () => {
  expect(decodeBase64(encodeBase64(textString))).toEqual(textString)
});

Answer №2

Make sure to utilize the btoa function for encoding strings

console.log(btoa("abc")); // YWJj

Similarly, you can use atob to decode the same string

console.log(atob("YWJj")); // abc

Answer №3

If you have previously utilized window.btoa(fileData) in the frontend code.

PLEASE NOTE: Following feedback from zerkms and a review of the package code, it appears that manual processing is sufficient. Although, I did need to run it twice to achieve success.
I was particularly attempting to decode a large image file.

In a Node.js server environment, you can directly utilize the Buffer solution:

const b64 = "SGVsbG8sIFdvcmxkIQ==";
const fileDataProcessed = Buffer.from(b64, 'base64').toString('binary')
const decodedData = Buffer(fileDataProcessed, 'base64')

// You can now proceed to upload this code snippet to your s3 bucket or any other destination.
console.log(decodedData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

express application functioning correctly with HTTP but encountering issues with HTTPS

Whenever I visit http://myurl.com/test, I see the message Reached me! on the page, just as expected. But, if I try to navigate to https://myurl.com/test, Chrome displays an error message stating Error: Cannot match any routes. URL Segment: 'test' ...

Leveraging Handlebars Object within JavaScript

Is there a way to pass an entire object into javascript directly? I've tried using the {{{data}}} and {{data}} methods as suggested in other posts, but it doesn't seem to be working for me. Here's what I have in my handlebars file: <scri ...

Mismatch in SSL version or cipher for ExpressJS

I am encountering an issue with https in express and I am struggling to comprehend it: Here is the code snippet from my previous project (which functions correctly): index.js: var fs = require('fs'); var http = require('http'); var ...

Storing an array of strings in an SQLite table column using Sequelizers

Is there a way to store an array of strings in a column and perform queries using this column? I attempted to use the JSON data type for the column, but I also need to make [Op.like] queries on this JSON column. For example: { actors: { [Op.like]: `% ...

Create typings for object properties in TypeScript

I am inexperienced with TypeScript and am looking to set up types for my object keys. I have explored a few methods to accomplish this, but I am encountering an issue where an error is not triggered when assigning a value of a different type. For example: ...

Step-by-step guide on receiving a file using the POST method in Postman or Next.js

Looking to send a file as an image or PDF using Postman with the POST method and form-data body type. However, encountering issues where no body is received in Express. The Node.js code being used is as follows: https://i.sstatic.net/F0mwvjjV.png The out ...

The Unhandled Promise Rejection Warning in mocha and ts-node is due to a TypeError that arises when attempting to convert undefined or null values

I've been encountering issues while setting up ts-node with mocha, as the test script consistently fails. I attempted to run the following commands: mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ ...

Can I pass mat-options to my custom mat-select component using ng-content?

I created a custom select component and attempted to utilize ng-content to pass in my options. Here is the code snippet I used: <lib-select [(selected)]="selected" (selectedChange)="onChange($event)"> <mat-option [value]="0">Value 1</ma ...

Issue with updating values in a ReactJS function

My ReactJs function is designed to display a simple dialogue box and update a value for the parent component. Here is an example of how the function is structured: export function MyDialogue(props: IMyProps) { var myValue = 0; return ( ...

Utilizing Angular in combination with Express-Handlebars for a Node.js project

I'm currently working on a node.js application with Express and express handlebars as the templating framework. Recently, I've been delving into Angular and trying to integrate it into my node.js app. However, I've encountered an issue wher ...

Storing Sessions in CouchDB Using Node.JS and Express.JS

Do I have the option to utilize Session Storage, or am I required to use MemoryStore? ...

Exploring Members in Mongodb Data Repository

Currently, I am utilizing mongodb with a user database. To enhance user experience, I want to enable users to search for other users in the database based on their username. Despite my attempts, I have not been successful in achieving this functionality ye ...

When I try to add a book to my cart in Angular 2, the system is mistakenly adding a duplicate copy instead of incrementing the quantity of

In my Angular 2 bookstore application, I have a method called selectedBook(b: Books) within the BookComponent. As the program runs, a table displays a list of books with each book having its own "Add to cart" button. When the Add to cart button is cl ...

Utilizing Observables for data filtration

I'm working with an array of objects that I want to filter. I had the idea to use Observables for this task. Can anyone confirm if this approach is correct? export class MyClass { public item1: string; public item2: string; } let myArray = M ...

Exploring the capabilities of argon2-browser in a cutting-edge setup with vite

After spending several hours attempting to implement the argon2-browser library in a Vue app with Vite, I have been encountering a persistent error. Despite following the documentation closely, I keep receiving the following message: This require call is ...

The error message related to TupleUnion in TypeScript is indicating that the depth of type instantiation may be too deep and could

Recently, I've been delving into a TypeScript utility type known as TupleUnion. This useful type came to my attention through a fascinating Twitter post, and I've observed it being utilized in various Stack Overflow solutions. Here's how the ...

Syncing Views with Callback Variables in Angular 2

Within my angular2 project, I am utilizing FileReader to read a csv file. Once the onloadend callback is triggered, a variable holds the content of the csv file. Below is a snippet from my component.ts : items: Array<any> = [] ... readCSV (event) ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

How to manage parameters within Express middleware

In my quest to organize my Express code, I find myself grappling with the dilemma of parameter handling. To illustrate, let's consider a scenario where I've crafted middleware that fetches data from a database: var loadMW = function (request, re ...

Display a popup in Angular 4 when a click event is triggered by a separate

I am currently facing an issue that I can't seem to solve. My objective is to display a popup div on the page when clicking on a menu entry in my navbar.component. In order to achieve this, I introduced a property called "show" in my popup component ...