admin管理员组文章数量:1404927
I want to load an image on a node.js file. But, when i try to fs.readfile, it errors out if there is no image file there after the server is running. 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.
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?
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 = '/' + 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-ic').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.
I want to load an image on a node.js file. But, when i try to fs.readfile, it errors out if there is no image file there after the server is running. 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.
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?
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./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-ic').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.
Share Improve this question asked Jul 27, 2015 at 17:18 Travis FinlanTravis Finlan 452 gold badges2 silver badges5 bronze badges 1- Have you tried just checking if the file exists before reading it?nodejs/api/fs.html#fs_fs_exists_path_callback – João Marcelo Brito Commented Jul 27, 2015 at 17:27
1 Answer
Reset to default 3The 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. To do what you would like to acplish (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./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-ic').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. 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.
Wele to Node.JS!
本文标签: javascriptHow do I load an image on a nodejs serverStack Overflow
版权声明:本文标题:javascript - How do I load an image on a node.js server? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744875523a2629891.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论