新人请教 数据流报错
发布于 8 年前 作者 yunkou 3152 次浏览 来自 问答
const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 1337;

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'image/png' });
  fs.createReadStream('./image.png').pipe(res);
}).listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

会报 Error: ENOENT: no such file or directory, open './image.png’ image.png 在js 当前目录。 求问,导致报错的原因和改如何解决

2 回复

'./image.png' 使用 path.resolve 的, 然后就是基于 process.cwd(), 要是 image.png 跟 js 一个目录, 可改为 __dirname + '/image.png'

@magicdawn 谢谢,在node 中没有按照预想的相对目录的关系,/Users/name/Documents/code/node-in-action/ 这样也可以,__dirname 相当于当前目录了。

至于你说的 path.resolve 还不会用,以后碰到再回来看看

问题解决了,谢谢。

回到顶部