2

像许多其他新手一样,我正在关注 Manuel Kiessling 的“The Node Beginner Book”。

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

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

我在我的项目中创建了文件夹“tmp”,并试图在那里发生同样的事情,但我只看到一个错误!

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

当我尝试路径时会发生同样的事情,tmp/test.png但有趣的是,当我将实际图像直接放入 tmp 文件夹并将其显示在我的页面上时,这两个路径都有效。所以语义/语法没有问题,或者..?

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

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;

值得注意的是,我专门放在那里进行故障排除的“Error 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.
4

1 回答 1

2

相对路径有效,但它们相对于process.cwd(),而不是当前执行的模块。

__dirname正在引用当前.js文件

于 2015-04-06T20:34:13.730 回答