Monday 12 June 2017

NodeJS: ENOENT: no such file or directory

I have a function that opens a file (if exists), returns it as response to an API call, and then deletes the file.

function getAttachment(req, res) {
  const filePath = req.params.filePath;
  try {
    const fileStream = fs.createReadStream(filePath);
    res.writeHead(200, { 'content-type': 'application/json' });
    fileStream.pipe(res);
    fs.unlinkSync(filePath);
  } catch (err) {
    console.log(JSON.stringify(err));
    res.sendStatus(404);
    res.end();
  }
}

However, I get this error:

2017-06-12T17:16:00.289105856Z {"errno":-2,"code":"ENOENT","syscall":"unlink","path":"data/myfile"}
2017-06-12T17:16:00.298763021Z events.js:160
2017-06-12T17:16:00.298781839Z       throw er; // Unhandled 'error' event
2017-06-12T17:16:00.298785330Z       ^
2017-06-12T17:16:00.298788100Z 
2017-06-12T17:16:00.298790660Z Error: ENOENT: no such file or directory, open 'data/myfile'
2017-06-12T17:16:00.298795535Z     at Error (native)
2017-06-12T17:16:00.306091265Z 
2017-06-12T17:16:00.312570210Z npm info lifecycle express-mongoose-es6-rest-api@1.0.0~start:dist: Failed to exec start:dist script
2017-06-12T17:16:00.312591284Z npm ERR! Linux 4.4.0-79-generic
2017-06-12T17:16:00.312763931Z npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "start:dist"
2017-06-12T17:16:00.312952665Z npm ERR! node v6.9.4
2017-06-12T17:16:00.313133777Z npm ERR! npm  v3.10.10
2017-06-12T17:16:00.313309768Z npm ERR! code ELIFECYCLE
2017-06-12T17:16:00.313484507Z npm ERR! express-mongoose-es6-rest-api@1.0.0 start:dist: `node dist/index.js`
2017-06-12T17:16:00.313491824Z npm ERR! Exit status 1
2017-06-12T17:16:00.313664060Z npm ERR!

How can I make this work without the system going down even if the file doesn't exist?



via Arturo

No comments:

Post a Comment