简体   繁体   English

如何在node.js服务器上加载图像?

[英]How do I load an image on a node.js server?

I want to load an image on a node.js file. 我想将图像加载到node.js文件上。 But, when i try to fs.readfile, it errors out if there is no image file there after the server is running. 但是,当我尝试fs.readfile时,如果服务器运行后那里没有图像文件,则会出错。 But, when i start my server, the image gets downloaded and displays and works correctly. 但是,当我启动服务器时,该图像将下载并显示并正常工作。

When i keep the server running and delete the image and try to refresh the page, hoping the image will be redownloaded and display still, it errors out on the fs.readfile because the image file isnt there because it does not redownload if it is deleted. 当我保持服务器运行并删除映像并尝试刷新页面时,希望映像将被重新下载并仍然显示,它在fs.readfile上出错,因为该映像文件不存在,因为如果删除该映像文件则不会重新下载。

How do i go about making the webpage dynamic so when i refresh localhost:1337, the image gets downloaded everytime, instead of just when the server is started? 如何使网页具有动态性,以便在刷新localhost:1337时每次都下载映像,而不仅仅是在启动服务器时下载映像?

Here is my code so far. 到目前为止,这是我的代码。

//Dilbert Comic Server
var http         = require('http'),
    fs           = require('fs'),
    request      = require('request'),
    url          = require('url'),
    cheerio      = require('cheerio'),
    request      = require('request'),
    DilbertURL   = 'http://Dilbert.com/strip/' + getDateTime();

http.createServer(function (req, res)
{
       var img = fs.readFileSync('./Dilbert.jpg');
       res.writeHead(200, {'Content-Type': 'image/gif' });
       res.end(img, 'binary');
      console.log('Server running at http://127.0.0.1:1337/');
}).listen(1337, '127.0.0.1');

request(DilbertURL, function (error, response, body) {
    var $ = cheerio.load(body);
    $('div.container-fluid').each(function(i, element){
      var src = $('.img-responsive.img-comic').attr("src");

      download(src, 'Dilbert.jpg', function()
      {
        console.log('Image downloaded');
      });
    });
});

var download = function(uri, filename, callback){
    request.head(uri, function(err, res, body){
      console.log('content-type:', res.headers['content-type']);
      request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
    });
};

function getDateTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + "-" + month + "-" + day ;
}

I am very new to Node.js, so bear with me please. 我对Node.js非常陌生,所以请多多包涵。

The problem with your code right now is that you are downloading the picture in what is known as the global scope, so when Node.JS loads the file and reads all the code, it sees that function and will run it just one time. 现在,您的代码存在的问题是,您正在以所谓的全局范围下载图片,因此,当Node.JS加载文件并读取所有代码时,它将看到该函数并将仅运行一次。 To do what you would like to accomplish (have the server download the picture every time) you have to put the download function inside of the function that executes when the web server receives a request, like so: 要完成您想完成的事情(服务器每次都要下载图片),您必须将下载功能放在当网络服务器收到请求时执行的功能的内部,如下所示:

//Dilbert Comic Server
var http = require('http'),
  fs = require('fs'),
  request = require('request'),
  url = require('url'),
  cheerio = require('cheerio'),
  DilbertURL = 'http://dilbert.com/strip/' + getDateTime();

 http.createServer(function(req, res) {

   request(DilbertURL, function(error, response, body) {
    var $ = cheerio.load(body);
    $('div.container-fluid').each(function(i, element) {
      var src = $('.img-responsive.img-comic').attr("src");

      download(src, 'Dilbert.jpg', function() {
        var img = fs.readFileSync('./Dilbert.jpg');
        res.writeHead(200, {
          'Content-Type': 'image/gif'
        });
        res.end(img, 'binary');
      });
    });
  });

}).listen(1337, '127.0.0.1', function(err){
  if(err){
    console.log("Failed to start web server:", err);
  }else{
    console.log('Server running at http://127.0.0.1:1337/');
  }
});

var download = function(uri, filename, callback) {
  request.head(uri, function(err, res, body) {
    console.log('content-type:', res.headers['content-type']);
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};
function getDateTime() {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  month = (month < 10 ? "0" : "") + month;
  var day  = date.getDate();
  day = (day < 10 ? "0" : "") + day;
  return year + "-" + month + "-" + day ;
}

NOTE: I cleaned up your code a little by performing the following fixes: 1) You were setting the request variable twice, so I removed the second one. 注意:我通过执行以下修复对代码进行了一些整理:1)您将请求变量设置了两次,因此删除了第二个。 2) You were printing out the 'Server running..' string every time the server got a request, so I made it print out when the server started without an error. 2)每次服务器收到请求时,您都在打印“服务器正在运行..”字符串,因此我在服务器启动时将其打印出来而没有错误。

Welcome to Node.JS! 欢迎使用Node.JS!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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