Render an image with nodejs - javascript

I am storing an image in mongodb with BinData type.
I can query the database using mongojs with this.
db.images.findOne({
file_name: 'temp.jpg',
},
function(err, data){
console.log(data.image); // image buffer appears on the console
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data.image);
});
This produces "TypeError: first argument must be a string or Buffer".
I am pretty sure this has something to do with buffers or encoding.
Can some please explain what I should be doing to the image-data before sending to the browser?

set the correct content type
set the correct content length
short example how i serve my files from mongodb gridfs
.getFileFromGridFs(doc,function(err, buffer){
if(err) return next(err)
res.setHeader('content-type',doc.mimeType)
res.setHeader('content-length',doc.size)
buffer.pipe(res)
})

Related

Find if a string is in a json file, then get the stuff around it

So I don't know a lot about JSON, I'm making a bot for a game that you can message and it sends you a code that you then send to my discord bot to link your account. I'm doing this by making it so whenever the bot is friended in game it accepts the request and sends a message to the user with a 5 Character code that is randomly generated and then stored in users.json with their player ID and Displayname. I'm done with the bot part mostly just the discord part now, I need to find if the code they input is in the json file and then get the displayName that goes with that code. If that makes sense...
Here's users.json with only one entry:
{"users":[{"name":"ImBattleDash","Id":"34a02cf8f4414e29b15921876da36f9a","code":"5MJS3"}]}
and here's the code to add to it:
fs.readFile('./users.json', 'utf-8', function(err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
arrayOfObjects.users.push({
name: userAuthorName,
Id: userAuthor,
code: authorCode
})
console.log(arrayOfObjects)
fs.writeFile('./users.json', JSON.stringify(arrayOfObjects), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
What I basically need is to search in the Json file for example if one of the codes is "5MZJ2" and if it is then get the name that goes with that and set it to a variable.
I've been trying to figure out how to do it but I'm still quite a beginner so some help would be appreciated!
A quick way to do it is to use the find() method, a solution would be:
let myCode = "5MJS3"
fs.readFile('./users.json', 'utf-8', function (err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
let myEntry = arrayOfObjects.users.find(entry => entry.code == myCode)
console.log(myEntry.name)
})
It basically go through your list and looks for an entry mathing the code :)

'database name must be a string' Error when connecting with my Connection String

I am attempting to connect to MongoDB via the package mongoose, but get an error along the lines of MongoError: database name must be a string.
I am using Windows, within the script I am also connecting to 2 other APIs which are both connected. I have tried adding my database name when requiring mongoose and also when connecting (.MyDatabaseName to the end).
Mongoose.connect("mongodb+srv://MyUserName:MyPassword#williamdata7kmxm.mongodb.net", {useNewUrlParser: true}).EternalsMilitary;
Mongoose.connect.once("open", function() {
console.log("Connected To MongoDB");
}).on("error", function(err) {
console.log("Error Connecting To MongoDB: ", err);
});
It's expected to output connected, but it errors with MongoError: database name must be a string.
I needed to include the database name inside of the URI string. For example... mongodb+srv://MyUserName:MyPassword#williamdata7kmxm.mongodb.net/MyDatabaseName
This will then point it to that specific database.
For whatever reason the new url parser doesn't seem to work with certain URLs.
As a quick fix you can try reverting back to the old one with { useNewUrlParser: false }
In your URI after where it says mongodb.net put slash and the name of the database for example:
mongoose.connect('mongodb+srv://<username>:<password>#<instance>.mongodb.net/**nameDatabase**', {dbName: "Eclipse"}, {useNewUrlParser: true})

Taking a Base64 Encoded Image and Sending it with ExpressJS as an Image

I'm working on a Node.JS application that utilizes ExpressJS as a web server.
I want to set up a route /get/thumbnail/by_guid/:guid that will return an image as a real image, not a base64 string, so I can set up the source of an image tag using <img src="/get/thumbnail/by_guid/ABCD" > and the actual image will display.
I'm storing the thumbnails as BLOBs in my database and am retrieving them. When I retrieve them, they become buffers in my node application. I'm then sending those buffers in my route as shown below, where img is a buffer object that contains the image.
router.get('/get/thumbnail/by_guid/:guid', function(req, res){
image_helper.guidToImage(req.params.guid).then(function(img){
res.set('Content-Type', 'image/jpeg');
res.set('Content-Length', img.length);
res.end(img, 'latin1');
}, function(err){
res.err(err);
});
});
guidToImage returns the image as a buffer.
When I go to the url described by a thumbnail I know at, for instance, /get/thumbnail/by_guid/ABCD, I see a white box like this:
When I look in the network tab of chrome dev tools, the request looks like this:
The response just shows my base64 string:
And the image shows as broken when I source it:
How can I achieve what I'm trying to do?
I've spent 6 hours trying to get this working right now.
Thanks for the help.
Changed route to get the binary to show properly.
router.get('/get/thumbnail/by_guid/:guid', function(req, res){
image_helper.guidToImage(req.params.guid).then(function(img){
var im = new Buffer(img.toString('binary'), 'base64');
res.writeHead(200, {
'Content-Type': 'image/jpg',
'Content-Length': im.length
});
res.end(im);
}, function(err){
res.err(err);
});
});

Store Image file in Binary data in mongoose schema and Display image in html form

I am using Express, Node.js, and Mongodb to create the webpage that uploads and displays the image file.
I saved the binary of image in mongodb using schema.
Here is my little bit of code in index.js and db.js..
var Post = mongoose.Schema({
image: {data: Buffer, contentType: String}
});
var post= new Post({ });
post.image.data=fs.readFileSync(req.file.path);
post.image.contentType='image/png';
and here is the part of mongo shell after I submitted image file and searched for post, and its image field
"image: {"data:BinData(0,"iVBORw0KGgoAAAANSUhEUE....(I
just cut off the rest of the code.. cuz it was too long)
rkJggg=="),
"contentType" : "image/png" }
so it seemed like it's successfully saving the binary data of image file in mogngodb,
but my problem is how to display the image on the webpage now using binary data. How do I convert binary buffer data to create image tag??
<img src= "data:{{image.contentType}};base64,{{image.data}}">
I tried this, but it gives me an error:
Failed to load resource: net::ERR_INVALID_URL
Could you guys please let me know how do I solve this??
I will really appreciate for your help :(((
First of all, you have to convert buffer data to base64. You can do it in back-end or front-end it does not matter. Just use yourBufferData.toString('base64'). Then you can use it.
However, I would suggest another way to store images instead of storing binary data. Assuming you use nodejs. You can create image in a repository with that binary data using fs.writeFile method. Then you can store that image path in record (db). AFter that, just put the file path into ng-src="file path which you saved". Here is the example which I use:
var path = 'upload/profiles/' +req.body.userId + '_profile.jpg';
fs.writeFile(path, base64data, function(err) {
if (err) return next(err);
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$set: {
profileImg: 'upload/profiles/' +req.body.userId + '_profile.jpg'
}
}, function(err, user) {
if (err) return next(err);
return res.send(user);
});
});
<img ng-src="savedpath">

D3.csv not loading the csv file

For some reason, I am not able to load any .csv file with the d3.csv(...) function. What I do is that I load a csv file using the function above and print out the data directly to the console.
This is what what I do:
I create a file called irisData.csv using notepad. It includes some data from the iris dataset from https://archive.ics.uci.edu/ml/datasets/Iris
sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
I write this code in my irisTest.html, to print out the data into the console, checking if it works correctly.
...
d3.csv("irisData.csv", type, function(error, data){
console.log(data);
});
...
Not sure if this is relevant, but I will put it up anyway: In order to run my html, I use Node.js to run a server. This is the code for the server, server.html:
var http = require('http');
fs = require('fs');
http.createServer(function(req, res){
fs.readFile('./irisTest.html', function(err, data){
if(err){
res.writeHead(500, {'Content-type': 'text/plain'});
res.end('500 - Internal Error');
}else{
res.writeHead(200, {'Content-type': 'text/html'});
res.end(data);
}
});
}).listen(3000);
So what I would expect is that the console prints out an object consisting of the data from the csv file. Something like this:
[
{data...}
{data...}
{data...}
...
]
However what I get is the code of my irisTest.html (which is the html code itself) wrapped into objects. I realize that it doesn't matter what I put instead of "irisData.cvs" as the path in d3.csv("irisData.csv", ...), it always outputs my own code such as below. So I thought it might be a problem with the path to the csv file, but there shouldn't be. All files are in the same folder.
[
...
{<!DOCTYPE html>: "d3.csv("irisData.csv", type, function(error, data){"}
{<!DOCTYPE html>: "console.log(data);"}
{<!DOCTYPE html>: "});}"}
...
]
Does anyone know what is going on?
As specified in the documentation here, the anonymous function is expected instead of type. I quote the example from the doc:
d3.csv("example.csv", function(d) {
return {
year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
make: d.Make,
model: d.Model,
length: +d.Length // convert "Length" column to number
};
}, function(error, rows) {
console.log(rows);
});
So, in your case, reading the csv file should be done this way:
d3.csv("irisData.csv",function(data){
console.log(data);
},function(error, rows){
console.log(rows);
});
Here is a working example in gist, check the console to see the data object.

Categories

Resources