Witam na mojej prywatnej stronie internetowej!
[If this is all Polish to you, click here: English]
Uwaga: z oczywistych powodów nie mogę zagwarantować swojej nieomylności, choć staram się o zgodność tego, co piszę, z Prawdą. Jest również oczywiste, że nie gwarantuję takiej zgodności w przypadku komentarzy. Umieszczenie linku do strony spoza niniejszego serwisu nie musi oznaczać, że podzielam poglądy autora tej strony, a jedynie, że uważam ją za wartościową z takich czy innych powodów.
Marcin ‘mbork’ Borkowski
Some time ago I wrote about a new-ish feature of Node where it parses .env files (dotenv-style) itself. Today, I’m going to mention a feature which has been in Node for some quite time, but somehow I’m not sure many people know about it.
We all know and love “printf debugging”, and I have written about its various variants I use quite a few times. However, sometimes just a console.log (or even console.dir) is not nearly enough. For example, you might want to know who called a function you are debugging. Normally, I’d put a console.trace() in such a function, but recently I learned that there is something better – or at least, more comprehensive.
For example, when you run this script with Node.js:
const fn = (arg) => {
console.log('inside `fn`', arg)
process.report.writeReport()
}
fn(1)
you get an output looking like this:
$ node report-test.js inside `fn` 1 Writing Node.js report to file: report.20260330.055029.225164.0.001.json Node.js report completed
When you look inside the generated json file, you’ll see several hundred lines of debugging goodness. Try it yourself to see what’s in there. Your stack trace can be found under javascriptStack, for example, but there’s a lot more. For example, all your environment variables are listed in the report (which makes it pretty important not to disclose it when they could contain secrets – but you can say process.report.excludeEnv = true to avoid listing them).
Of course, if all you need is a stack trace and you are not really interested in details like memory consumption, CLI arguments, the process id of your Node program or the OS version you ran, you might as well use console.trace. Where this feature really shines is in the ways of triggering the report creation. The writeReport function is just one of them. For example, you can make Node generate a report when an uncaught error is thrown:
const fn = (arg) => {
console.log('inside `fn`', arg)
throw new Error("custom exception")
}
process.report.reportOnUncaughtException = true
fn(1)
Other options are fatal error (which may mean a Node.js bug or an OOM error) or – perhaps most interestingly – a signal (SIGUSR2 by default). That means you can set your Node app up to generate a report on demand and request a report with kill -SIGUSR2 <pid>. Head to the docs to learn more about this cool feature!