6

i am trying tp get phantomjs webserver works for me

I want to serve 2 files, html file , and a png image file, the html file is served well and rendered 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 html file markup

<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 the browser, the png file is not rendered, and even if i tried to point the browser to the png file, it does not render it

i checked with the chrome developer tools the network status and it confirm that the file is fully downloaded by the browser

what is wrong?

by the way, i have to use phantomjs, please d not tell me to use another server

thanks

Joe

4

3 回答 3

7

这对我有用(假设你有响应对象):

  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();
于 2016-04-13T08:05:11.693 回答
2

如果您正在读取 PNG 文件,我相信您的 fs.open() 调用应该将“rb”用于二进制读取模式。模式“r”适用于您的 html,因为它是文本,但是虽然它仍会读取 PNG 文件并将其提供给浏览器,但图像数据是不可渲染的。

于 2013-10-26T05:55:00.230 回答
-2

您正在尝试使用异步函数,就好像它们是同步的一样。您使用的所有文件系统函数(exists()open()read())都是异步的,并尝试调用具有所需结果的回调(您没有提供);他们不这样做return。要么使用这些函数的同步版本,要么(更好)学习如何使用异步 I/O。

于 2012-06-20T14:13:07.753 回答