为什么我可以使用绝对path而不是相对的方式将带有Formidable的file upload到文件夹?

和其他许多新手一样,我正沿着Manuel Kiessling的“The Node Beginner Book”继续学习。

我们应该通过Formidable模块来启动图像上传,不断地将图像重命名为“test.png”并显示。

本书使用path/tmp/test.png ,一切工作正常。 但是这不是一个相对path,我的图像实际上保存在Linux的tmp文件夹中!

我在我的项目中创build了文件夹“tmp”,并试图使相同的事情发生在那里,但我只显示一个错误!

 ENOENT, open './tmp/test.png' 

当我尝试pathtmp/test.png时,同样的事情发生,但有趣的部分是,当我把一个实际的图像直接放入tmp文件夹并将其显示在我的页面上时,这两个path都起作用。 所以没有语义/语法错误,或..?

我的requestHandler.js,其中重要的部分是上传和显示function:

 var querystring = require("querystring"), fs = require("fs"), formidable = require("formidable"); function start(response) { console.log("Request handler 'start' was called."); var body = '<html>' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; ' + 'charset=UTF-8" />' + '</head>' + '<body>' + '<form action="/upload" enctype="multipart/form-data" ' + 'method="post">' + '<input type="file" name="upload" multiple="multiple">' + '<input type="submit" value="Upload file" />' + '</form>' + '</body>' + '</html>'; response.writeHead(200, {"Content-Type": "text/html"}); response.write(body); response.end(); } function upload(response, request) { console.log("Request handler 'upload' was called."); var form = new formidable.IncomingForm(); console.log("about to parse"); form.parse(request, function(error, fields, files) { console.log("parsing done"); fs.rename(files.upload.path, "./tmp/test.png", function(err) { if (err) { console.log("Error Flynn"); fs.unlink("./tmp/test.png"); fs.rename(files.upload.path, "./tmp/test.png"); } }); response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); } function show(response) { console.log("Request handler 'show' was called."); fs.readFile("./tmp/test.png", "binary", function(error, file) { if(error) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(error + "\n"); response.end(); } else { response.writeHead(200, {"Content-Type": "image/png"}); response.write(file, "binary"); response.end(); } }); } exports.start = start; exports.upload = upload; exports.show = show; 

值得注意的是,我错误地发现“错误Flynn”错误消息排除故障确实被调用,并将文件放在文件夹中删除!

这里是日志:

 Request for /upload received. About to route a request for /upload Request handler 'upload' was called. about to parse parsing done Error Flynn fs: missing callback Error: ENOENT, unlink './tmp/test.png' fs: missing callback Error: EXDEV, rename '/tmp/upload_9bcb8afa8cd2f78ff52c294edd106965' Request for /show received. About to route a request for /show Request handler 'show' was called. 

相对path工作,但它们是相对于process.cwd()而不是当前正在执行的模块。

__dirname引用了当前的.js文件