如何在node.js中给出文件路径?

时间:2014-05-08 05:54:05

标签: node.js express download

我正在将文件从一个驱动器下载到本地系统中的另一个驱动器。这是我用过的代码:

upload.js:
   var fs = require('fs')
   var newPath = "E:\\Thevan";
   var oldPath = "E:\\Thevan\\Docs\\something.mp4";

   exports.uploadFile = function (req, res) {
   fs.readFile(oldPath, function(err, data) {
    fs.writeFile(newPath, data, function(err) {
        fs.unlink(oldPath, function(){
            if(err) throw err;
            res.send("File uploaded to: " + newPath);
        });
      });
   });
};

app.js:
   var express = require('express'), // fetch express js library
   upload = require('./upload'); // fetch upload.js you have just written
   var app = express();
   app.get('/upload', upload.uploadFile); 
   app.listen(3000);

当我运行上面的代码时......它给出错误"错误:EISDIR,打开' E:\ Thevan'"。 如何在上面的代码中给出路径或出错?

1 个答案:

答案 0 :(得分:2)

使用路径的最佳方式 - 使用path模块(API):

path模块:

var path = require('path');
path.join('E:','Thevan','Some File.mp4');

如果您切换到Linux,它还可以解决更多问题。

但您还有另一个问题 - 您将DIRNAME而不是FILENAME传递给writeFile函数。我想你的意思是:

var newPath = "E:\\Thevan\\something.mp4";
var oldPath = "E:\\Thevan\\Docs\\something.mp4";