Node.js NPM string-to-arraybuffer Module

02 Feb, 2022
NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called ‘shortid’ used to short non-sequential url-friendly unique ids.
Command to install:  
npm install string-to-arraybuffer
Syntax to import the package in local file
const str2ab = require('string-to-arraybuffer')
Syntax to convert string to an array buffer
const arrBuff = str2Ab(string)
Parameters : It takes one parameter ‘string’ that we wants to convert in array buffer.
Example 1: This example illustrates how to use ‘string-to-arraybuffer to convert from string to array buffer.
Filename – index.js : This file contains logic to convert string to array buffer.
Javascript
const express = require('express')const bodyParser = require('body-parser')const str2Ab =require('string-to-arraybuffer')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => {  res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => {  const {str} = req.body   // Converting from utf8 string to array buffer  const arrBuffer = str2Ab(str)     // Create view of array buffer  const view = new Int8Array(arrBuffer)     // Printing on console  console.log(`Original string : ${str}\n`)  console.log('ArrayBuffer :' + view)}) // Server setupapp.listen(port, () => {  console.log(`Server start on port ${port}`)})
Filename-form.js : This file contain logic to render the form.
Javascript
module.exports = ({errors}) => {  return `<!DOCTYPE html><html> <head>  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'>  <style>    div.columns {      margin-top: 100px;    }     .button {      margin-top: 10px    }  </style></head> <body>  <div class='container'>    <div class='columns is-centered'>      <div class='column is-5'>        <form action='/' method='POST'>          <div>            <div>              <label class='label' id='str'>                String              </label>            </div>            <input class='input' type='text'              name='str' placeholder=              'string(plain text/base64/dataURI)'              for='str'>          </div>          <div>            <button class='button is-info'>              Submit            </button>          </div>        </form>      </div>    </div>  </div></body> </html>  `}
Output:
Submitting utf8(plain text) string to convert it to array buffer
Response printed in command prompt when submitting the plain text(utf8) string
Submitting base64 input string to convert it to array buffer
Response printed in command prompt when submitting the base64 string
Note: Look at the response in both cases, since the submitted string is same although in different form, their array buffer view is also same. 
Example 2: In this example  we use both ‘string-to-arraybuffer’ and ‘arraybuffer-to-string’ to illustrates the transparency between them. we use plain text string here to convert it from one form to other form.
Filename – index.js : This file contains logic to convert plain text string to array buffer and again decode it to plain text string.
Javascript
const express = require('express')const bodyParser = require('body-parser')const str2Ab = require('string-to-arraybuffer')const ab2Str = require('arraybuffer-to-string')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => {  res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => {  const {str} = req.body   // Converting from utf8 string to array buffer  const arrBuffer = str2Ab(str)     // Create view of array buffer  const view = new Int8Array(arrBuffer)   // Decode string from array buffer  const decodedStr = ab2Str(arrBuffer)     // Printing on console  console.log(`Original string : ${str}\n`)  console.log(`Array Buffer : ${view}\n`)  console.log(`Decoded String: ${decodedStr}`)}) // Server set to runapp.listen(port, () => {  console.log(`Server start on port ${port}`)})
Filename-form.js : This file contain logic to render the form.
Javascript
module.exports = ({errors}) => {  return `<!DOCTYPE html><html> <head>  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'>  <style>    div.columns {      margin-top: 100px;    }     .button {      margin-top: 10px    }  </style></head> <body>  <div class='container'>    <div class='columns is-centered'>      <div class='column is-5'>        <form action='/' method='POST'>          <div>            <div>              <label class='label' id='str'>                Plain text string              </label>            </div>            <input class='input' type='text'              name='str' placeholder=              'plain text string' for='str'>          </div>          <div>            <button class='button is-info'>              Submit            </button>          </div>        </form>      </div>    </div>  </div></body> </html>  `}
Output:
Submitting plain text string
Response printed in command prompt when submitting the plain text string
Example 3: In this example, we use both string-to-arraybuffer and arraybuffer-to-string to illustrates the transparency between them. we use base64 string here to convert it from one form to other form.
Filename – index.js : This file contains logic to convert base64 string to array buffer and again decode it to base64 string.
Javascript
const express = require('express')const bodyParser = require('body-parser')const str2Ab = require('string-to-arraybuffer')const ab2Str = require('arraybuffer-to-string')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => {  res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => {  const {str} = req.body   // Converting from base64 string to array buffer  const arrBuffer = str2Ab(str)     // Create view of array buffer  const view = new Int8Array(arrBuffer)   // Decode base64 string from array buffer  // using arraybuffer-to-string package  const decodedStr = ab2Str(arrBuffer, 'base64')     // Printing on console  console.log(`Original string : ${str}\n`)  console.log(`Array Buffer : ${view}\n`)  console.log(`Decoded String: ${decodedStr}`)}) // Server setupapp.listen(port, () => {  console.log(`Server start on port ${port}`)})
Filename-form.js : This file contain logic to render the form.
Javascript
module.exports = ({errors}) => {  return `<!DOCTYPE html><html> <head>  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'>  <style>    div.columns {      margin-top: 100px;    }     .button {      margin-top: 10px    }  </style></head> <body>  <div class='container'>    <div class='columns is-centered'>      <div class='column is-5'>        <form action='/' method='POST'>          <div>            <div>              <label class='label' id='str'>                Base64 string              </label>            </div>            <input class='input' type='text'              name='str' placeholder=              'base64 string' for='str'>          </div>          <div>            <button class='button is-info'>              Submit            </button>          </div>        </form>      </div>    </div>  </div></body> </html>    `}
Output:
Submitting base64 string
Response printed in command prompt when submitting the base64 string
Note:  We have used some Bulma classes in form.js file to design the content.
mridulmanochagfg
sagartomar9927
sweetyty
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React