• Stars
    star
    247
  • Rank 164,117 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

He is like Batman, but for Node.js stack traces

Stackman

Give Stackman an error and he will give an array of stack frames with extremely detailed information for each frame in the stack trace.

With Stackman you get access to the actual source code and surrounding lines for where the error occurred, you get to know if it happened inside a 3rd party module, in Node.js or in your own code. For a full list of information, check out the API below.

npm Build status js-standard-style sponsor

Install

npm install stackman

Basic usage

var stackman = require('stackman')()

var err = new Error('Oops!')

stackman.callsites(err, function (err, callsites) {
  if (err) throw err

  callsites.forEach(function (callsite) {
    console.log('Error occured in at %s line %d',
      callsite.getFileName(),
      callsite.getLineNumber())
  })
})

Gotchas

error.stack

This module works because V8 (the JavaScript engine behind Node.js) allows us to hook into the stack trace generator function before that stack trace is generated. It's triggered by accessing the .stack property on the Error object, so please don't do that before parsing the error to stackman, else this will not work!

If you want to output the regular stack trace, just do so after parsing the callsites:

// first call stackman.callsites with the error
stackman.callsites(err, function () {...})

// then you can print out the stack trace
console.log(err.stack)

Stackman API

var stackman = Stackman([options])

This module exposes a single function which you must call to get a stackman object.

The function takes an optional options object as its only argument. These are the available options:

  • fileCacheMax - When source files are read from disk, they are kept in memory in an LRU cache to speed up processing of future errors. You can change the max number of files kept in the LRU cache using this property (default: 500)
  • sourceMapCacheMax - When source maps are read from disk, the processed source maps are kept in memory in an LRU cache to speed up processing of future errors. You can change the max number of source maps kept in the LRU cache using this property (default: 100)

stackman.callsites(err[, options], callback)

Given an error object, this function will call the callback with an optional error as the first argument and an array of CallSite objects as the 2nd (a call site is a frame in the stack trace).

Note that any error related to loading or parsing source maps will be suppressed. If a source map related error occurs, Stackman behaves as if the sourcemap option is false.

Options:

  • sourcemap - A boolean specifying if Stackman should look for and process source maps (default: true)

var properties = stackman.properties(err)

Given an error object, this function will return an object containing all the custom properties from the original error object (beside date objects, properties of type object and function are not included in this object).

stackman.sourceContexts(callsites[, options], callback)

Convenience function to get the source context for all call sites in the callsites argument in one go (instead of iterating over the call sites and calling callsite.sourceContext() for each of them).

Calls the callback with an optional error object as the first argument and an array of source context objects as the 2nd. Each element in the context array matches a call site in the callsites array.

Options:

  • lines - Total number of lines of soruce context to be loaded with the call site line in the center (default: 5)
  • inAppLines - Total number of lines of soruce context to be loaded with the call site line in the center if callsite.isApp() is true. Overwrites lines (default: 5)
  • libraryLines - Number of lines of soruce context to be loaded with the call site line in the center if callsite.isApp() is false. Overwrites lines (default: 5)

All node core call sites and call sites where no lines were collected due to the above options being 0, will have the context value null.

CallSite API

A CallSite object is an object provided by the V8 stack trace API representing a frame in the stack trace. Stackman will decorate each CallSite object with custom functions and behavior.

callsite.sourcemap

If source map support is enabled and a source map have been found for the CallSite, this property will be a reference to a SourceMapConsumer object representing the given CallSite.

If set, all functions on the CallSite object will be source map aware. I.e. their return values will be related to the original source code and not the transpiled source code.

var val = callsite.getThis()

Inherited from V8

Returns the value of this.

To maintain restrictions imposed on strict mode functions, frames that have a strict mode function and all frames below (its caller etc.) are not allow to access their receiver and function objects. For those frames, getThis() will return undefined.

var str = callsite.getTypeName()

Inherited from V8

Returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property.

var str = callsite.getTypeNameSafely()

A safer version of callsite.getTypeName() that safely handles an exception that sometimes is thrown when using "use strict" in which case null is returned.

var fn = callsite.getFunction()

Inherited from V8

Returns the current function.

To maintain restrictions imposed on strict mode functions, frames that have a strict mode function and all frames below (its caller etc.) are not allow to access their receiver and function objects. For those frames, getFunction() will return undefined.

var str = callsite.getFunctionName()

Inherited from V8

Returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context.

var str = callsite.getFunctionNameSanitized()

Guaranteed to always return the most meaningful function name. If none can be determined, the string <anonymous> will be returned.

var str = callsite.getMethodName()

Inherited from V8

Returns the name of the property of this or one of its prototypes that holds the current function.

var str = callsite.getFileName()

Inherited from V8 if callsite.sourcemap is undefined

If this function was defined in a script returns the name of the script.

var str = callsite.getRelativeFileName()

Returns a filename realtive to process.cwd().

var num = callsite.getLineNumber()

Inherited from V8 if callsite.sourcemap is undefined

If this function was defined in a script returns the current line number.

var num = callsite.getColumnNumber()

Inherited from V8 if callsite.sourcemap is undefined

If this function was defined in a script returns the current column number.

var str = callsite.getEvalOrigin()

Inherited from V8

If this function was created using a call to eval returns a CallSite object representing the location where eval was called.

Note that since Node.js v12.11.0, this function returns undefined unless eval was used.

var str = callsite.getModuleName()

Returns the name of the module if isModule() is true. Otherwise returns null.

var bool = callsite.isToplevel()

Inherited from V8

Is this a toplevel invocation, that is, is this the global object?

var bool = callsite.isEval()

Inherited from V8

Does this call take place in code defined by a call to eval?

var bool = callsite.isNative()

Inherited from V8

Is this call in native V8 code?

var bool = callsite.isConstructor()

Inherited from V8

Is this a constructor call?

var bool = callsite.isApp()

Is this inside the app? (i.e. not native, not node code and not a module inside the node_modules directory)

var bool = callsite.isModule()

Is this inside the node_modules directory?

var bool = callsite.isNode()

Is this inside node core?

callsite.sourceContext([lines, ]callback)

Get the source code surrounding the call site line.

If the callsite is a node core call site, the callback will be called with an error.

Arguments:

  • lines - Total number of lines of soruce context to be loaded with the call site line in the center (default: 5)
  • callback - called when the source context have been loaded with an optional error object as the first argument and a source context object as the 2nd

Source Context

The source context objects provided by callsite.sourceContext contains the following properties:

  • pre - The lines before the main callsite line
  • line - The main callsite line
  • post - The lines after the main callsite line

Troubleshooting

To enable debug mode, set the environment variable DEBUG=stackman.

Acknowledgements

This project was kindly sponsored by Elastic.

License

MIT

More Repositories

1

awesome-computer-history

An Awesome List of computer history videos, documentaries and related folklore
2,500
star
2

airplanejs

πŸ“‘ ✈️ App that picks up ADS-B radio signals from airplanes and plots them in real time on a map in your browser
JavaScript
649
star
3

bonjour

A Bonjour/Zeroconf protocol implementation in JavaScript
JavaScript
604
star
4

ipp-printer

An IPP printer written in Node.js
JavaScript
533
star
5

worker-threads-pool

Easily manage a pool of Node.js Worker Threads
JavaScript
426
star
6

is-ci

Detect if the current environment is a CI server
JavaScript
384
star
7

ci-info

Get details about the current Continuous Integration environment
JavaScript
317
star
8

airplay-server

A low level AirPlay server
JavaScript
260
star
9

base64-emoji

Like base64 but encoding into emojis β­βœŠβ˜•
JavaScript
124
star
10

console-log-level

The most simple logger imaginable
JavaScript
111
star
11

monster-drift

πŸ“»πŸŽ Drive a radio controlled car with Node.js and HackRF
JavaScript
106
star
12

airplay-protocol

A low level protocol wrapper on top of the AirPlay HTTP API
JavaScript
104
star
13

airserver

Node.js AirPlay server
JavaScript
98
star
14

progress-string

Get a progress bar as a string
JavaScript
93
star
15

rtsp-stream

A transport agnostic RTSP serial multiplexer module for Node
JavaScript
87
star
16

workload

πŸ€– Workload sends HTTP requests to a server to mimic a natual load
JavaScript
79
star
17

airplayer

Query your local network for Apple TV's and have them play videos
JavaScript
79
star
18

http-echo-server

A simple HTTP echo server
JavaScript
78
star
19

memory-usage

Sample memory usage for your Node.js program and write the samples to a stream
JavaScript
73
star
20

rtl-sdr

A modern Node.js wrapper around the librtlsdr library
C++
73
star
21

request-stats

Get stats on your Node.js HTTP server requests
JavaScript
72
star
22

original-url

Reconstruct the original URL used in an HTTP request based on the HTTP request headers
JavaScript
70
star
23

wifi-triangulate

Finds your current position on planet earth using the wifi access points in your vicinity
JavaScript
68
star
24

chart-stream

Chart time series data from either STDIN or programmatically from any Node.js app in real time directly in your browser
CSS
65
star
25

talks

A collection of slides and related code for talks that I've given
HTML
63
star
26

http-traceroute

A command line tool for following and showing HTTP redirects for a given URL
JavaScript
60
star
27

bcc

An IPP tool to Man-in-the-Middle all traffic to a local printer
JavaScript
60
star
28

ipp-encoder

Internet Printing Protocol (IPP) encoder and decoder
JavaScript
60
star
29

printbin

A way to install a printbin printer
Shell
56
star
30

test-all-versions

Run your test suite against all published versions of a dependency
JavaScript
51
star
31

libmodes

A Mode S / ADS-B decoder library
C
48
star
32

code-status

Check if any of your git projects needs attention
JavaScript
47
star
33

uuid-benchmark

Benchmark of different UUID generation methods in Node.js πŸ’πŸš€
JavaScript
43
star
34

reverse-http

A reverse HTTP client
JavaScript
41
star
35

git-state

Get the current state of any git repository
JavaScript
40
star
36

bonjour-browser

A command line tool to browse for Bonjour/Zeroconf enabled services on your local network
JavaScript
39
star
37

event-debug

Log all events emitted by a Node.js EventEmitter object
JavaScript
38
star
38

http-headers

HTTP header string parser
JavaScript
37
star
39

nodeboat

Copenhagen -> Oslo -> Copenhagen @ Sep 20th to 22nd
CSS
35
star
40

secret-event-listener

Add an event listener without causing any side effects
JavaScript
34
star
41

chart-csv

Chart a comma separated list of numbers on a line-graph that can be viewed in a web browser
HTML
34
star
42

npm-dependency-db

Query npm dependents of a certain version or version range of a given package
JavaScript
33
star
43

aircat

AirPlay cat tool
JavaScript
33
star
44

mode-s-demodulator

A JavaScript module for demodulating and decoding Mode S / ADS-B messages from aviation aircrafts
JavaScript
31
star
45

roundround

A dead simple round-robin array iterator
JavaScript
30
star
46

hash-index

A hashing function which returns integers with a possible max value
JavaScript
29
star
47

rtsp-server

A low level module for creating RTSP servers
JavaScript
29
star
48

old-unix-spell-checker

A modern recreation of the UNIX spell checker example from "The UNIX Operating System" video
Shell
29
star
49

cheerio-advanced-selectors

Add advanced selector support to cheerio
JavaScript
29
star
50

mongodown

A drop-in replacement for LevelDOWN that runs on MongoDB
JavaScript
28
star
51

https-pem

Self-signed PEM key and certificate ready for use in your HTTPS server
JavaScript
27
star
52

stream-chopper

Chop a single stream of data into a series of readable streams
JavaScript
27
star
53

geocode-wifi

Returns a latitude and a longitude given an array of wifi access points
JavaScript
26
star
54

is-lambda

Detect if your code is running on an AWS Lambda server
JavaScript
25
star
55

dns-txt

Encode/decode DNS-SD TXT record RDATA fields
JavaScript
22
star
56

flatten-obj

Converts an object literal with deeply nested nodes to a simple key/value object
JavaScript
20
star
57

raop-rtsp-server

A RAOP server in Node.js
JavaScript
20
star
58

npm-to-hypercore

Stream all of npm metadata into hypercore
JavaScript
19
star
59

stream-observer

Listen for data events on a readable stream without triggering flowing mode
JavaScript
19
star
60

frequency-counter

Count the number of occurrences of a repeating event per unit of time
JavaScript
18
star
61

cheerio-eq

Add :eq() selector functionality to cheerio
JavaScript
17
star
62

is-secret

A distributed maintained collection of patterns that indicate that something probably is secret
JavaScript
17
star
63

throttling

Throttle a function and cache the result for x milliseconds
JavaScript
16
star
64

json2mongo

A MongoDB Extended JSON conversion utility which converts Strict Mode syntax to JavaScript Mode
JavaScript
15
star
65

photodrop

An AirPlay enabled website to showcase your cool photos
JavaScript
15
star
66

slice-lines

Fast algorithm for extracting a subset of lines from a string
JavaScript
15
star
67

geopkg

πŸ“‘ Tag npm moduels with lat/long of where on the planet the module was published 😜
JavaScript
15
star
68

download-to-file

Download a file to disk programmatically
JavaScript
14
star
69

34c3

Chaos Communication Congress 2017 Schedule for the Command Line
JavaScript
14
star
70

redact-secrets

Deeply iterate over an object and redact secret values by replacing them with a predefined string
JavaScript
14
star
71

http-teapot

Add support for RFC 2324 to any HTTP server
JavaScript
13
star
72

hotswap-module

Replace a Node.js module with another module without any code changes
JavaScript
13
star
73

mode-s-decoder

A library to decode a binary Mode S message to an easy to use JavaScript object
JavaScript
13
star
74

raop-server

A simple RAOP server
JavaScript
12
star
75

tick-id

Give each tick on the Node.js event loop it's own ID
JavaScript
12
star
76

msgpack5-stream

A duplex stream wrapper for msgpack5
JavaScript
12
star
77

virtual-grid

A viewport into a virtual grid of text cells
JavaScript
12
star
78

mongohooks

A thin before/after filter extension for the mongojs node-module.
JavaScript
11
star
79

menu-string

Generate a menu with selectable menu items as a string
JavaScript
11
star
80

consume-until

Consume a stream until a given pattern is found
JavaScript
11
star
81

printcat

Output print jobs to STDOUT
JavaScript
11
star
82

fast-stream-to-buffer

Consume a stream of data into a binary Buffer as efficiently as possible
JavaScript
11
star
83

git-ps1

A simple command line prompt enhancer that shows the state of the current git repo (ps1)
Shell
10
star
84

normalize-bool

Converts strings representing an on/off-state to booleans
JavaScript
10
star
85

mongo-restful

A very simple MongoDB RESTful proxy
JavaScript
10
star
86

mostly-working-hours

Call a callback mostly during normal working hours
JavaScript
10
star
87

is-it-weekend

Returns true if it's Saturday or Sunday, otherwise it returns false
JavaScript
10
star
88

nth-indexof

Find the nth position of a pattern in a string
JavaScript
10
star
89

npm-available

CLI & module to check if a given module name is available on npm
JavaScript
10
star
90

librtlsdr-dongle-validator

A static website for testing USB device compatibility with the librtlsdr library
JavaScript
10
star
91

object-stream-map

Perform a map on a stream of objects
JavaScript
10
star
92

fork-proxy

Proxy a single incomming TCP connection to multiple remote TCP servers
JavaScript
10
star
93

after-all-results

Like after-all, but collects the results for you
JavaScript
9
star
94

tweetcat

p2p pipe across the internet using Twitter as a transport stream
JavaScript
9
star
95

airplay-mdns-server

An AirPlay mDNS broadcast server
JavaScript
9
star
96

mode-s-aircraft-store

A utility library for keeping track of active aircrafts and their position based on their Mode S messages
JavaScript
9
star
97

simple-sqs

A simple wrapper around the AWS SQS queue service
JavaScript
9
star
98

require-ancestors

Returns the chain of JavaScript files used to require a given Node module - i.e. its ancestors
JavaScript
9
star
99

github-stats

A collection of sites that will show you nice stats from GitHub
9
star
100

printbin-printer

The IPP printer behind http://printb.in
JavaScript
9
star