node.jsexpressmultiparty

fs writeFile create temp file in app root


I have the following code snippet to up[load files to server. Its working as expected in local environment but not in web server.

Using connect-multiparty

path = req.files.FIELDNAME.path;
ogname = req.files.video.originalFilename;

function(path , ogname, callback) {
var fs = require('fs');
var uploadDir = process.cwd() + "/public/uploads/";
fs.readFile(path, function (err, data) {
  var originalFilename = new Date().getTime() + '-' + ogname.replace(/[\s,:-]+/g, "-");
  var newPath = uploadDir + originalFilename;
  var relatPath = "/uploads/" + originalFilename;
  fs.writeFile(newPath, data, function (err,result) {
    callback(relatPath);
  });
});
}

It creates files in /public/uploads as expected but leaves something in app root too. Like this

enter image description here


Solution

  • https://github.com/andrewrk/connect-multiparty

    This middleware will create temp files on your server and never clean them up.

    You have to delete them manually:

    //....
    fs.writeFile(newPath, data, function (err,result) {
        callback(relatPath);
        fs.unlink(path, function (err) {
            if (err) throw err;
        });
    });
    

    Note that process.cwd() does not return the app root path, but the working directory. Use __dirname instead.

    And using rename is much faster and saves you from having to delete the file manually.