Why there's no Stack Trace in node fs.rmdir Error

Viewed 363

When the directory is not empty the fs.rmdir throws an error without the stack trace:

{ [Error: ENOTEMPTY: directory not empty, rmdir '/var/folders/cv/fhzhp3gn/T/downloads']
  errno: -66,
  code: 'ENOTEMPTY',
  syscall: 'rmdir',
  path:
   '/var/folders/cv/fhzhp3gn/T/downloads' }

For comparison I tried throwing fake error explicitly, see fake_delete_directory and it shows the stack trace (note the /alex/projects/play.js:8:67 line):

Error: some error
    at Timeout.setTimeout [as _onTimeout] (/alex/projects/play.js:8:67)
    at listOnTimeout (timers.js:324:15)
    at processTimers (timers.js:268:5)

The code:

const fs = require('fs')

function delete_directory(path) {
  return new Promise((resolve, reject) => fs.rmdir(path, (err) => err ? reject(err) : resolve()))
}

function fake_delete_directory(path) {
  return new Promise((resolve, reject) => setTimeout(() => reject(new Error("some error"), 1)))
}

const main = async () => {
  const path = '/var/folders/cv/fhzhp3gn/T/downloads'
  await delete_directory(path)
}

main().catch((e) => console.error(e))

Why fs.rmdir does not have the stack trace? And how to add it? It's very difficult to debug and track down such errors.

1 Answers

Node's fs functions throws Errors without a stack trace. This is by design, here's an issue tracker for more info: https://github.com/nodejs/node/issues/30944

You can use a third-party package like trace to get the complete stack trace. It only works with node.js v8.x and newer. You'll have to launch node with some extra args though:

node --stack_trace_limit=100 -r trace script.js
Related