Nodes serving permanent image

I am trying to load an image file in node.js. The file will be in the plunger and loaded beyond the main loop. Its just 1x1 pixel.

How to open an image file?

I tried the following:

var fs = require('fs');
fs.readFile('/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/pixel1x1.gif', function(err,pixel){
  if(err) {
    console.error("Could not open file: %s", err);
    process.exit(1);
  }
  console.log(pixel);
});


Server running at http://127.0.0.1:8124/
<Buffer 47 49 46 38 39 61 01 00 01 00 80 00 00 00 00 00 ff ff ff 21 f9 04 01 00 00 00 00 2c 00 00 00 00 01 00 01 00 00 02 01 44 00 3b>

Image cannot be displayed because it contains errors.

 res.writeHead(200, {'Content-Type': 'image/gif'});
 res.end(pixel);
+3
source share
1 answer

If this is just a 1x1 gif image, you don’t need to store the image file and download it, because there is a good service pack for NPM that already has an empty 1x1 gif loaded with the base64 line directly in the code, so it will work faster than loading the image separately. In addition, there is some helper function that can help you send this image to expressjs.

, :

var blankgif = require('blankgif');
var express = require('express');
var app = express();

app.get('/track.gif', blankgif.sendBlankGif);

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

, , - . , :

1) ,

var blankgif = require('blankgif');
var express = require('express');
var app = express();

app.use(blankgif.middleware());

app.get('/track.gif', function(req, res) {
  console.log('request information logged');

  res.set('Cache-Control', 'public, max-age=0');
  res.status(200).sendBlankGif();
});

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

2) blankgif.sendBlankGif

var blankgif = require('blankgif');
var express = require('express');
var app = express();

app.get('/track.gif', function(req, res, next) {
  console.log('request information logged');
  next();
}, blankgif.sendBlankGif);

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

, - ( gif), :

var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');

var buff = null;

fs.readFile(path.resolve(__dirname, 'pixel1x1.gif'), function (err, pixel) {
  if (err) {
    console.error("Could not open file: %s", err);
    process.exit(1);
  }

  buff = pixel;
});

app.get('/track.gif', function (req, res) {
  console.log('request information logged');

  res.type('image/gif');
  res.send(buff);
});

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});
+1

All Articles