简体   繁体   中英

how can I transfer output raw images through Node.JS?

For example; I have a check looking to see if the request URL is "/favicon.ico". I would like to simply output that image without the need for fs. Of course I'll need to change the content-type headers accordingly, but how should I insert actual image in the JS file, without getting a parse error?

I've tried the simplest thing: opening the image in a txt editor, and pasting contents into a variable. I figured it would be efficient to keep all of my files in memory, since it's a simple site.

You could use a data uri to include the images in your source. I don't know enough about Node.JS to tell you how to programmatically do it, but since you were just going to store them in variables anyway it should be easy to convert the images to data uris and store those in vars. Most modern browsers (and IE8+) support data uris. If you search for "data uri generator" you should find plenty of them online.

I personally like the Base64 Encoder extension for Firefox. It is a quick and convenient way to make data uri images when I need them.

Update

After a little more research, you could maybe store a base64 encoded string and then load it into a Buffer and do something like this:

var image1 = new Buffer('iVBORw0KGgoAAAANSUhEUgAAABQAAAAHCAIAAACHqfpvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABlSURBVChTjVDJDQAgCGMuB2Iep3EZh0GEqiQekQ8htLSFmGKlXOW/yKCFicsvqeYE8IGsS5gBRk97dV9x2MjrruIsBdo09lCel03LteEFRt7kS3wlmZPRRQ6Zg3YHrxeMpzpAdw2MaCJX2CUsrAAAAABJRU5ErkJggg==', 'base64');
response.writeHead(200, {
    'Content-Length': image1.length,
    'Content-Type': 'image/png'
});
response.end(image1);

It looks like you could even do it with the copy-pasted raw data using the "binary" encoding with a Buffer, but that has been deprecated so I'd stick with something more reliable like base64.

Use Buffer.from , as Buffer is deprecated, will get the following warning

(node:15707) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

var image1 = Buffer.from(('iVBORw0KGgoAAAANSUhEUgAAABQAAAAHCAIAAACHqfpvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABlSURBVChTjVDJDQAgCGMuB2Iep3EZh0GEqiQekQ8htLSFmGKlXOW/yKCFicsvqeYE8IGsS5gBRk97dV9x2MjrruIsBdo09lCel03LteEFRt7kS3wlmZPRRQ6Zg3YHrxeMpzpAdw2MaCJX2CUsrAAAAABJRU5ErkJggg==', 'base64');
response.writeHead(200, {
    'Content-Length': image1.length,
    'Content-Type': 'image/png'
});
response.end(image1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM