在node.js中放置图像文件的位置
Where to put the image file in node.js?
我在Linux中有以下目录结构,其中只有3个文件:
/home/nikhil/test_img/
- server.js
- page.html
- pic.jpg
这是一个简单的node.js hello world设置,不使用express或任何其他库
server.js代码
var http = require("http"), fs = require('fs');
var path = require('path');
var root = path.dirname(require.main.filename);
var filePath = path.join(root + '/page.html');
var port = 8889;
function onRequest(request, response) {
fs.readFile(filePath, function (err, html) {
if (err) {
throw err;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(html);
response.end();
});
}
http.createServer(onRequest).listen(port, function () {
console.log("Server has started at port " + port);
});
这只是创建一个服务器,在对localhost的任何请求时显示page.html:
page.html代码
<html>
<head><title>Page</title></head>
<body>
<h1> Hello World </h1>
<img src="pic.jpg" alt="image">
</body>
</html>
这是一个带有Hello World标题和图片的简单网页。
现在,错误是当我在浏览器上点击localhost:8889加载页面时,图像没有显示出来。但是,当我通过浏览器(不是通过节点)打开网页时,图像就会显示出来。
我也尝试将src更改为
- "/home/nikhil/test_img/page.html"
- "文件:///home/nikhil/test_img/page.html"
- "localhost: 8889/page.html"但是,这些都不起作用
另外,我尝试使用<script>alert(document.location.pathname);</script>
打印的路径是
/
然而,当我直接在浏览器中运行页面(没有节点)时,它是
/home/nikhil/test_img/page.html
我需要把这个工作的图像文件在哪里?
你的代码说,每个请求应该服务的文件对应于filePath
即html文件page.html
。这对于页面请求本身是可以的,但是html页面中的img
标记为图像pic.jpg
创建了一个单独的请求,该图像应该存在于与页面相同的路径中。但是,不是提供img文件,这意味着您的请求处理程序将返回头为Content-type: image/jpg
的内容,您的请求处理程序再次响应html页面的内容和头为Content-Type:text/html
。
相关文章:
- 将包含SVG元素的HTML转换为图像文件
- 由多个图像文件组成的响应地图
- 使用文件夹路径名保存所有图像文件和文件名
- 如何将 html5 画布另存为窗口 8 Metro 应用程序中的图像文件
- 将图像文件存储在猫鼬模式中的二进制数据中,并以html形式显示图像
- 如何使用heatmap.js保存canvas标记生成的图像文件
- 如何使用html / angularjs保存图像文件
- 如何从 HTML 或 Javascript for Windows Phone 访问图像文件
- 在 Windows 现代(地铁)UI 应用中存储图像文件和音频文件的方法是什么?
- 节点 js 流星 js 图像文件上传图像损坏
- 从图像URL javascript html保存图像文件
- 如何使用AJAX读取图像文件并渲染到Canvas
- 浏览器和大量的图像文件处理
- 什么错误I'我在下面的jQuery代码中集成filepicker.io来上传一个图像文件
- 节点:将 base64 源写入图像文件
- 如何将图像文件以及JavaScript变量的值上传到服务器和数据库
- 如何从本地文件夹(磁盘存储)读取或获取图像文件,并使用nodejs服务器将其发送到Angularjs
- 如何使用expressnodejs上传图像文件并进行显示
- 如何用我在HTML5画布上绘制的src保存图像文件
- 图像文件因websocket文件传输而损坏