Maisum Abbas
Maisum Abbas

Reputation: 359

How to resolve path issues while moving files in node.js?

I am trying to get a file from html form and store it in another folder. It's basically cloud function, and I am new to both node.js and firebase so don't know what I am doing wrong. What I manage to do is:

const fileMiddleware = require('express-multipart-file-parser');

app.post("/sendMail", (req, res) => {
const {
    fieldname,
    filename,
    encoding,
    mimetype,
    buffer,
  } = req.files[0];
  console.log(req.files[0].originalname);
  var fs = require('fs')

  var oldPath = req.files[0].originalname;
  var newPath = '/functions/'+oldPath;

  fs.rename(oldPath, newPath, function (err) {
      if (err) throw err
      console.log('Successfully renamed - AKA moved!')
  });
});

Whenever I try to move file, I got path issues. The error is as follows:

[Error: ENOENT: no such file or directory, rename 'C:\Users\Maisum Abbas\now\functions\sendMail.txt' 
> 'C:\functions\sendMail.txt'] {    
>    errno: -4058,
>    code: 'ENOENT',
>    syscall: 'rename',
>    path: 'C:\\Users\\Maisum Abbas\\now\\functions\\sendMail.txt',
>    dest: 'C:\\functions\\sendMail.txt'
>  }

Also, this is the path where I want to actually move the file but oldpath is already setup like this.

C:\Users\Maisum Abbas\now\functions\sendMail.txt 

Upvotes: 2

Views: 1487

Answers (3)

Maisum Abbas
Maisum Abbas

Reputation: 359

Since I needed to attach a file with email, it was causing path issues. I tried it with multer and it works. What I did:

//call libraries here

var storage =   multer.diskStorage({
    destination: function (req, file, callback) {
    callback(null, 'resume/');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage}).single('filetoupload');

app.post("/careerMail", (req, res) => {
  const { name } = req.body;
  const { email } = req.body;
  const { phone } = req.body;
  upload(req,res,function(err) {
    if(err) {
        return res.end("Error uploading file.");
    }
  });

const dest = 'mymail';

const mailOptions = {
    from: email, // Something like: Jane Doe <[email protected]>
    to: dest,
    subject: 'Candidate Application', // email subject
    html: `<div>             
    <strong>From:</strong> ` +
          name +
          `<br /><br />              
    <strong>Email:</strong> ` +
          email +
          `<br /><br />              
    <strong>Phone:</strong> ` +
          phone +
          `<br /><br />           
    </div>           
    `,// email content in HTML
    attachments: [
      {
          filename: req.files[0].originalname,
          content: req.files[0].buffer.toString("base64"),
          encoding: "base64"
      }
    ]

and rest of the code...

Upvotes: 2

Muhammad Saquib Shaikh
Muhammad Saquib Shaikh

Reputation: 298

I ran into same problem while moving file. I sort this problem by using a function to get the application root folder and then concatenate rest of the location.

//place this file on application root.
//import where you need to get the root path.

const path = require('path');
module.exports = (function(){
    return path.dirname(require.main.filename || process.mainModule.filename);
})();

//taking your case move location.

const rootPath = //require the above module.

const newPath = rootPath + /functions/' +oldPath;

 fs.rename(oldPath, newPath, function (err) {
      if (err) throw err
      console.log('Successfully renamed - AKA moved!')
  });

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317467

I suggest rethinking this approach altogether. You won't be able to move files around in a deployed function. The nodejs runtime filesystem doesn't allow any files to be written anywhere in the filesystem, except for os.tmpdir() (which is /tmp on Linux).

If you need to write a file temporarily, you should definitely only use that tmp space. Be aware that files written there occupy memory and should be deleted before the function terminates, or you could leak memory.

You can read files that you deployed with your code, but you should do that through relative paths.

Upvotes: 0

Related Questions