Erlpil
Erlpil

Reputation: 15

Buffer base64 encode a variable, node.js

I am trying to encode a variable from a http parameter to base64 using node.js and buffer.

My code:

var http = require("http");
var url = require("url");

http.createServer(function(req, res) {

  var parsedUrl = url.parse(req.url, true);
  var queryAsObject = parsedUrl.query;
  var urlEncodeString = new Buffer(queryAsObject).toString('base64');

  console.log(urlEncodeString);

  res.end(urlEncodeString);

}).listen(8020);

console.log("Server listening on port 8020");

URL used: http://127.0.0.1:8020/?test=testtxt

The queryAsObject returns { test: ‘testtxt’ }

Is there a way to use the Buffer to read the variable queryAsObject and encode it with base64 ?

I have spent a good amount of hours searching for ways to make the buffer accept this variable, but I can not find a way that works.

Upvotes: 0

Views: 1024

Answers (1)

mscdex
mscdex

Reputation: 106746

You need to JSON.stringify() your object first.

Change:

var urlEncodeString = new Buffer(queryAsObject).toString('base64');

to:

var urlEncodeString = new Buffer(JSON.stringify(queryAsObject)).toString('base64');

Upvotes: 1

Related Questions