Cannot deliver image files via phantomjs web server

I'm trying to use tp get phantomjs webserver for me

I want to serve 2 files, an html file and a png image file, the html file is displayed correctly and correctly in the browser, but the png file is not

here is the code for the server

var fs = require('fs'); function loadFile(name){ if(fs.exists(name)){ console.log(name+ " File exist"); return fs.open(name,"r"); }else { console.log("File do not exist"); } } var server, service; server = require('webserver').create(); service = server.listen(8080, function (request, response) { if(request.url.split(".")[1] === "html" ){ var fi = loadFile("./test.html"); response.statusCode = 200; response.write(fi.read()); fi.close(); response.close(); }else if (request.url.split(".")[1] === "png"){ var fi = loadFile("./output_87.png"); response.headers = {"Content-Type":"image/png"}; response.statusCode = 200; response.write(fi.read()); fi.close(); response.close(); } }); 

and this is the markup of the html file

 <html> <head><title>title</title></head> <body><h1> Hello world </h1> <img src="output_87.png" alt="image"> </body> </html> 

when viewing this file in a browser, the png file is not displayed, and even if I tried to point the browser to the png file, it will not display it

i checked the status of the network using the developer’s chrome tools and confirmed that the file was fully downloaded by the browser

what's wrong?

By the way, I have to use phantomjs, please don't tell me to use another server

thanks

Joe

+6
source share
3 answers

This works for me (if you have a response object):

  var fs = require("fs"); var image = fs.open("image.png", "rb"); var data = image.read(); image.close(); response.setHeader("Content-Type", "image/png"); response.setEncoding("binary"); response.write(data); response.close(); 
+7
source

I believe your fs.open () call should use "rb" for binary read mode if you are reading a PNG file. The "r" mode works for your html because it is text, but for now it will still read the PNG file and submit it to the browser, the image data will not be displayed.

+2
source

You are trying to use asynchronous functions as if they were synchronous. All file system functions that you use ( exists() , open() and read() ) are asynchronous and try to call a callback (which you do not supply) with the desired result; they do not return it. Use either synchronous versions of these functions, or (much better) learn how to use asynchronous I / O.

-2
source

Source: https://habr.com/ru/post/918516/


All Articles