Skip to content
Related Articles

Related Articles

Node.js NPM string-to-arraybuffer Module
  • Last Updated : 10 Feb, 2021

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 data
app.use(bodyParser.urlencoded({extended : true}))
 
// Get route to display HTML form
app.get('/', (req, res) => {
  res.send(formTemplet({}))
})
 
// Post route to handle form submission logic and
app.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(`Orginal string : ${str}\n`)
  console.log('ArrayBuffer :' + view)
})
 
// Server setup
app.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=
  <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 promt when submitting the plain text(utf8) string

Submitting base64 input string to convert it to array buffer

Response printed in command promt 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 data
app.use(bodyParser.urlencoded({extended : true}))
 
// Get route to display HTML form
app.get('/', (req, res) => {
  res.send(formTemplet({}))
})
 
// Post route to handle form submission logic and
app.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(`Orginal string : ${str}\n`)
  console.log(`Array Buffer : ${view}\n`)
  console.log(`Decoded String: ${decodedStr}`)
})
 
// Server set to run
app.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=
  <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 promt 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 data
app.use(bodyParser.urlencoded({extended : true}))
 
// Get route to display HTML form
app.get('/', (req, res) => {
  res.send(formTemplet({}))
})
 
// Post route to handle form submission logic and
app.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(`Orginal string : ${str}\n`)
  console.log(`Array Buffer : ${view}\n`)
  console.log(`Decoded String: ${decodedStr}`)
})
 
// Server setup
app.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=
  <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 promt when submitting the base64 string

Note:  We have used some Bulma classes in form.js file to design the content.

My Personal Notes arrow_drop_up
Recommended Articles
Page :