我有一个打开文件的函数(如果存在),将其作为对API调用的响应返回,然后删除该文件。
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();
}
}
然而,我收到此错误:
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!
即使文件不存在,如果系统不停机,如何才能完成这项工作?