dgnk
dgnk

Reputation: 98

How to use node js (Buffer) in google apps script

I want to execute this node js line in google apps script. How do I use this line in google apps script:

const payload = new Buffer(JSON.stringify(obj)).toString('base64');

When I run it I got this error:

ReferenceError: Buffer is not defined

Upvotes: 4

Views: 2102

Answers (2)

Tanaike
Tanaike

Reputation: 201613

I believe your goal as follows.

  • You want to convert const payload = new Buffer(JSON.stringify(obj)).toString('base64'); in Node.js to Google Apps Script.

Unfortunately, in the current stage, new Buffer() and Buffer.from() cannot be used with Google Apps Script. So in this case, I think that Utilities.base64Encode can be used for your situation. The sample script is as follows.

Sample script:

const obj = {key: "value"};
const payload = Utilities.base64Encode(JSON.stringify(obj));
console.log(payload)  // eyJrZXkiOiJ2YWx1ZSJ9

Result:

When above script is run, eyJrZXkiOiJ2YWx1ZSJ9 is retrieved. In this case, I could confirm that the result value is the same with the following Node.js script.

const obj = {key: "value"};
const payload = new Buffer(JSON.stringify(obj)).toString('base64');
// or const payload = Buffer.from(JSON.stringify(obj)).toString('base64');
console.log(payload)  // eyJrZXkiOiJ2YWx1ZSJ9

Reference:

Upvotes: 6

Buffer is used in nodeJS

The equivilant in client side JavaScript is array buffer

In order to make one from a string, you have to make a uint8array or Uint16Array from a new array buffer object with the length of the string, then loop through the array and add the char code values from the string at the index, and return the buffer

A function

function Buffer(str) {
    var buf= new ArrayBuffer(str.length/*multiply by 2 for higher chars*/)
    var ar = new Uint8Array(buf) //use Uint16Array etc for larger, i=0
    for(i=0;i< ar.length;i++) ar[i] = str.charCodeAt(I)
    return buf
}

Upvotes: 0

Related Questions