const fs = require('fs');
async function read() {
return fs.promises.readFile('non-exist');
}
read()
.then(() => console.log('done'))
.catch(err => {
console.log(err);
})
gives:
➜ d2e2027b node app.js
[Error: ENOENT: no such file or directory, open 'non-exist'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'non-exist'
}
➜ d2e2027b
The stack is missing. If I use fs.readFileSync instead, it shows the stack as expected.
➜ d2e2027b node app.js
Error: ENOENT: no such file or directory, open 'non-exist'
at Object.openSync (node:fs:582:3)
at Object.readFileSync (node:fs:450:35)
at read (/private/tmp/d2e2027b/app.js:4:13)
at Object.<anonymous> (/private/tmp/d2e2027b/app.js:8:1)
As a super-ugly-workaround, I can put try/catch and throw a new error in case of ENOENT but I'm sure there is a better solution out there.
read()
.then(() => console.log('done'))
.catch(err => {
if (err.code === 'ENOENT') throw new Error(`ENOENT: no such file or directory, open '${err.path}'`);
console.log(err);
})
(I tried node v12, v14, v16 - same same)