I am working on running different encoding statements based on the URL.
My code:
var parsedUrl = url.parse(req.url, true);
var queryAsObject = parsedUrl.query;
var myString = queryAsObject["string"];
var myFunction = queryAsObject["function"];
if (myFunction == "encodeb64") {
var bufEncode = new Buffer(JSON.stringify(myString));
var myEncode = bufEncode.toString('base64');
console.log(myEncode);
}
else {
console.log("Error1");
};
if (myFunction == "decodeb64") {
// var bufDecode = new Buffer(myEncode, 'base64');
// var myDecode = bufDecode.toString('utf8');
var myDecode = new Buffer(myEncode, 'base64').toString('utf8');
console.log(myDecode);
}
else {
console.log("Error2");
};
URL used: http://127.0.0.1:8020/?string=text&function=decodeb64
The issue is that I am having is with the last if statement. If its looking for decodeb64 and the first statement is looking for encodeb64 it crashes when function=decodeb64 is in the URL. If both if statements are looking for either encodeb64 or decodeb64, it runs perfectly. It also works if function=encodeb64 is in the URL.
The error message I get is:
buffer.js:188
throw new TypeError('First argument needs to be a number, ' +
^
It points to:
var myDecode = new Buffer(myEncode, 'base64').toString('utf8');
The given number on the error is pointed to the n in new.
I have located the problem to be inside the decode if statement by moving and reversing the order on the code.
As you can see in my code notes, I have tried two different methods of decoding with no success.
The reason that it crashes I believe is that when function=decode64, the variable myEncode is not declared and initialized, as the if(myFunction=="encode64") block is not run. So when the code tried to new Buffer(myEncode...) it would fail as myEncode is undefined. I think you meant to code :
var myDecode = new Buffer(myString, ...)
instead