Convert base64 image to a file in Node Js - javascript

I am new to Node Js. I need to include a profile image for users. I get request of image in base64 from IOS app. I need to store it in images folder and save the image path in mongodb database.
I have used the following code,
var bitmap = new Buffer(req.body.profile_image, 'base64');
// write buffer to file
fs.writeFileSync("images/example.jpg", bitmap);
where req.body.profile_image is a base64 image.
I am getting the following error,
TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
req.body.profile_image value will be,
+MZScHeJQ9Cz5dfxnEmIMHWMZyZYnYx8Rrhj0HbtfGUanv5w3UHUyADbiGsKJxeM1yV4uGwBS7cYlAec1w0AX6xg2A1O854UF8OS6PAP1MtzkeFnrNlD41U8XFeGrp1fn3jRMUs8sqS61umSS2rR2NDhppjZ4OvnOWBAq6X+sQNkhKkfZOdYsZOpz8fWIQb6wQ/GchVCgfZko4PMDg1DSumausG6o+2E6wKLLjKReUaHEQXKJV8h85XEKN4p/WEBvTHmmJ/IN178YJVgrGmfOScAuBPp+sggGA7/wC1kgbDiacbGABOcCLHVRpMuBQh5Xn4xqARF03pwkJT23LhxGLiSGp8mCVWDrzPf3iwp4C3nDSg2VUfNwgDvm6vrIiFJvp8ZHIdjoFx8BX0OH0+8TVii3GAKKc2kjz7dYqUCdsuMOm2hrr+h//Z
Please help.

Edit: This code worked for me. Maybe the error happens later.
var fs = require("fs");
var image = "+MZScHeJQ9Cz5dfxnEmIMHWMZyZYnYx8Rrhj0HbtfGUanv5w3UHUyADbiGsKJxeM1yV4uGwBS7cYlAec1w0AX6xg2A1O854UF8OS6PAP1MtzkeFnrNlD41U8XFeGrp1fn3jRMUs8sqS61umSS2rR2NDhppjZ4OvnOWBAq6X+sQNkhKkfZOdYsZOpz8fWIQb6wQ/GchVCgfZko4PMDg1DSumausG6o+2E6wKLLjKReUaHEQXKJV8h85XEKN4p/WEBvTHmmJ/IN178YJVgrGmfOScAuBPp+sggGA7/wC1kgbDiacbGABOcCLHVRpMuBQh5Xn4xqARF03pwkJT23LhxGLiSGp8mCVWDrzPf3iwp4C3nDSg2VUfNwgDvm6vrIiFJvp8ZHIdjoFx8BX0OH0+8TVii3GAKKc2kjz7dYqUCdsuMOm2hrr+h//Z";
var bitmap = new Buffer(image, 'base64');
fs.writeFileSync("images/example.jpg", bitmap);
If you said
console.log(req.body.profile_image)
rather than
console.log(typeof req.body.profile_image)
It would cast what ever data is in req.body.profile_image to a string before printing. Its possible you just forgot the 'typeof' when commenting, but if you didn't add the 'typeof' you can't be certain that it contains a string. There's more than one constructor to Buffer and it may be using the wrong one.
For the lolz try:
Buffer.from(String.fromCharCode.apply(null, new Uint16Array(req.body.profile_image)), "base64")
What gets assigned to req.body.profile_image?
The first argument to writeFileSync is a string, so it can't be causing the type error. Can you be more specific as to what is contained in req.body.profile_image?
On a side note, although I think this is unrelated to your problem, instantiating a Buffer with the 'new' keyword is deprecated.
Maybe using Buffer.from(...) will move you in the direction of a solution.

Related

Reading windows registry Reg_SZ in javascript

first time posting here!:)
As title says I have a win reg fie (reg_sz) which contains "name" and "value"
this.reg = new Registry.Key(Registry.windef.HKEY.HKEY_CURRENT_USER, 'Path\Path\Path', Registry.windef.KEY_ACCESS.KEY_READ);
funct read(this.reg){
var value;
var pushes = [];
[
"food",
"veggy",
"etc",
"etc"].forEach(function(name) {
try {
value = key.getValue(name);
entries.push({name: name, value: value});
} catch (e) {
}
});
return pushes;
};
example: "food"="apple"
Which my code reads properly, however I came across a issue with special characters, example "ä"
"food"="äpple"
which my code reads as �pple.
My question is what kind of decoding/encoding should i use and what is with this win registry, what exactly are they using? Can it be raw JS preferably and if not what else? I tried using decodeURI/encodeURI but seems like its not the correct approach(dont know what encoding they are using and which decoding should I use)
TLDR: How can i type in "äpple" in win registry and when reading that file with JS get same "äpple" instead of "�pple"
It looks like you're using windows-registry-node. This is unfortunately a bug in that, #44. The reporter says:
If i return the raw buffer and use iconv to convert from "ISO-8859-1" to "UTF-8" i get the correct characters
Note that this is assuming the current code page of the system, though, and might not always be correct. (It might be possible to tell iconv to detect and use the current code page?)
The exact problem is in registry.js:
// READ VALUE
result = advApi.RegQueryValueExA(key.handle.deref(), valueName, null, pKeyType, value,
pKeyDataLength);
Here it uses RegQueryValueExA, which means fetch strings as the current Windows code page, as opposed to RegQueryValueExW which would use UTF-16. So value, which is a Node.JS Buffer, does not contain UTF-8. The code then calls Buffer.toString(), which assumes UTF-8 by default:
if (value.type === types.LPTSR) {
// TODO not sure why buffer's utf8 parsing leaves in the unicode null
// escape sequence. This is a work-around (at least on node 4.1)
value = value.toString().replace('\u0000', '');
}
So this is going to need a fix in windows-registry-node. The best fix is probably to set the code up for UTF-16, using the -W version of the function and value.toString('utf16le');

extendscript: get Filepath of Project

Iam trying to get the current Filepath of my After Effects project (not Jsx)
var path=app.project['file'];
this variable "path" is giving me the a current FileObject name but it is a File-Object not a String. I need the alert as String. Or is there even a better way to get the Path as String?
Take a look at the File Object in the Object Model Viewer within Extendscript Toolkit or here.
if(app.project.file !== null){
var path = app.project.file.fsName;
$.writeln(path);
}

readFileSync won't work with me. I tried to print the input after setting it to string but was weird

Im new to Node.js and I'm trying to learn alone. I have a simple task to do the following:
-read a file (supplied buy the first command line argument).
-print the number of lines in the file.
-I am using the readFileSync method.
The code is running but the output is weird. I tried printing every statement, and I think the problem is in the reading of the data. Can anyone please tell me where I'm wrong?
function numLines(){
var fs = require('fs');
var num = 0;
var contents = fs.readFileSync(process.argv[0]);
console.log(contents.toString());
return num;
}
disregard the return statement, please just focus on the readFileSync. While printing the contents, the text printed is full of weird characters, as if the reading is going wrong
var contents = fs.readFileSync(process.argv[0]);
process.argv[0] is not the first argument passed to your script, actually. It's the command node. The second item is the filename of the your script, which is passed to node, assuming you're calling it as node myscript.js somefile.txt. You need to get the third item: process.argv[2]
See https://nodejs.org/api/process.html#process_process_argv
Without an encoding, readFile and readFileSync give you back a raw buffer you have to interpret in the correct encoding yourself (rather than just calling toString on it). From the docs:
If no encoding is specified, then the raw buffer is returned.
So either specify the encoding of the file in the readFileSync call, or use a buffer methods to read it using a given encoding. The Buffer docs talk about the encodings supported by Node, such as utf8.
So for instance, if your file is in UTF-8, you'd use:
function numLines(){
var fs = require('fs');
var num = 0;
var contents = fs.readFileSync(process.argv[0], {encoding: 'utf8'});
console.log(contents.toString());
return num;
}
More: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

How to save the file input data to a variable in javascript

İ tried to do it simply by assign the files of the input into a variable:
var files = document.getElementById("upload").files;
but there seems to be a connection created with this assign so every time the input changes the variable changes too.
so how can I do that without this connection?
You just want the filenames? Then just get the filenames :
var files = [],
upload = document.getElementById("upload");
upload.onchange = function() {
for (var i=0;i<upload.files.length;i++) {
files.push(upload.files[i].fileName);
}
}
??? No "inherited" behaviour from FileList, but I assume I misunderstand.
That's because it's being used as a reference to the files property. If you don't know what that means, do some reading on Google for "pass by value vs pass by reference."
What you need to do to copy the value unfortunately is something like this:
var files = (function() { return document.getElementById("upload").files; })();
In order to copy the value with no reference to the .files property.
The simplistic answer of what is happening here is that var files references the memory address of the files property of that DOM element. It looks to you like it's copying the value when in fact it is pointing to that memory slot and access it is just following a trail to whatever is stored there and accessing it.
I have modified #Mike's answer and came to a result where it actually works. I am writing the answer for a single file which can be converted to support multiple files.
var file = document.getElementById("upload").files[0]
this will store the file and not the refrence to the file hence if the value of upload file type changes the value in file remains unchanged.
Hope this might help someone else

js-ctypes from javascript objects

I'm working on a Firefox extension that receives binary images as ArrayBuffers of uint8_t.
In my extension I load a .dll file that has a function that I need to use on that received image. The function takes a ctype.uint8_t.ptr parameter and returns a ctype.uint8_t.ptr value.
I can't seem to find a way of converting the ArrayBuffer to this particular ctype so that I can pass it along to the function. Is there a correct way to do this?
Using ImplicitConvert() gives an Error: argument must be a nonnegative integer.
You should be able to do just:
var a = new Uint8Array(1<<10);
var ptr = new ctypes.uint8_t.ptr(a.buffer);
The stuff is not documented it seems, but there are some tests that demonstrate this.

Categories

Resources