0
# Stack Trace
1
2
Stack Trace is a Node.js library that provides utilities for capturing and parsing V8 stack traces as arrays of CallSite objects. It offers two main functions: capturing current stack traces using V8's native stack trace API, and parsing existing Error objects' stack properties using regex-based parsing.
3
4
## Package Information
5
6
- **Package Name**: stack-trace
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install stack-trace`
10
11
## Core Imports
12
13
```javascript
14
const stackTrace = require("stack-trace");
15
```
16
17
Destructured import:
18
19
```javascript
20
const { get, parse } = require("stack-trace");
21
```
22
23
## Basic Usage
24
25
```javascript
26
const stackTrace = require("stack-trace");
27
28
// Capture current stack trace
29
const trace = stackTrace.get();
30
console.log(trace[0].getFileName()); // Current file name
31
console.log(trace[0].getFunctionName()); // Current function name
32
33
// Parse existing error stack
34
const err = new Error("something went wrong");
35
const parsedTrace = stackTrace.parse(err);
36
console.log(parsedTrace[0].getFileName()); // Error file name
37
```
38
39
## Architecture
40
41
Stack Trace is built around two complementary approaches for accessing V8 stack trace information:
42
43
- **Native V8 Integration**: The `get()` function uses V8's `Error.prepareStackTrace` and `Error.captureStackTrace` APIs to capture live stack traces with full CallSite object support
44
- **Regex-based Parsing**: The `parse()` function analyzes Error stack strings using regular expressions to extract stack frame information when native access isn't available
45
- **CallSite Factory Pattern**: Internal `CallSite` constructor and `_createParsedCallSite()` factory provide consistent object interface regardless of data source
46
- **Cross-boundary Support**: Integration with long-stack-traces module enables stack trace continuity across asynchronous boundaries
47
- **Graceful Degradation**: Robust error handling ensures the library works even with malformed or incomplete stack data
48
49
## Capabilities
50
51
### Stack Trace Capture
52
53
Captures the current execution stack as an array of CallSite objects using V8's native stack trace API.
54
55
```javascript { .api }
56
/**
57
* Captures current stack trace as array of CallSite objects
58
* @param {Function} [belowFn] - Optional function to exclude from trace
59
* @returns {CallSite[]} Array of CallSite objects representing the stack
60
*/
61
function get(belowFn);
62
```
63
64
**Usage Examples:**
65
66
```javascript
67
const stackTrace = require("stack-trace");
68
69
// Get full stack trace
70
function myFunction() {
71
const trace = stackTrace.get();
72
console.log("Called from:", trace[1].getFunctionName());
73
}
74
75
// Get stack trace excluding current function
76
function excludeMe() {
77
const trace = stackTrace.get(excludeMe);
78
// trace[0] will be the caller of excludeMe, not excludeMe itself
79
console.log("Real caller:", trace[0].getFunctionName());
80
}
81
```
82
83
### Stack Trace Parsing
84
85
Parses an Error object's stack property into an array of CallSite-compatible objects using regex-based parsing.
86
87
```javascript { .api }
88
/**
89
* Parses Error object's stack property into array of CallSite objects
90
* @param {Error|Object} err - Error object or object with stack property
91
* @returns {CallSite[]} Array of CallSite objects, empty array if no stack
92
*/
93
function parse(err);
94
```
95
96
**Usage Examples:**
97
98
```javascript
99
const stackTrace = require("stack-trace");
100
101
// Parse error stack trace
102
try {
103
throw new Error("Oops!");
104
} catch (err) {
105
const trace = stackTrace.parse(err);
106
trace.forEach((site, i) => {
107
console.log(`${i}: ${site.getFunctionName()} at ${site.getFileName()}:${site.getLineNumber()}`);
108
});
109
}
110
111
// Handle malformed stacks gracefully
112
const badError = { stack: "corrupted\nstack\ntrace" };
113
const trace = stackTrace.parse(badError); // Returns filtered, valid entries only
114
115
// Handle missing stack property
116
const noStack = {};
117
const emptyTrace = stackTrace.parse(noStack); // Returns []
118
```
119
120
### CallSite Objects
121
122
The CallSite objects returned by both `get()` and `parse()` implement the V8 CallSite API with methods for accessing stack frame information.
123
124
```javascript { .api }
125
/**
126
* CallSite object representing a single frame in the stack trace
127
*/
128
interface CallSite {
129
/** Returns the value of this */
130
getThis(): any;
131
/** Returns the type name of this as a string */
132
getTypeName(): string | null;
133
/** Returns the current function */
134
getFunction(): Function | null;
135
/** Returns the name of the current function */
136
getFunctionName(): string | null;
137
/** Returns the name of the property holding the current function */
138
getMethodName(): string | null;
139
/** Returns the name of the script file */
140
getFileName(): string | null;
141
/** Returns the current line number */
142
getLineNumber(): number | null;
143
/** Returns the current column number */
144
getColumnNumber(): number | null;
145
/** Returns eval origin if created using eval */
146
getEvalOrigin(): string | null;
147
/** Returns true if this is a top-level invocation */
148
isTopLevel(): boolean;
149
/** Returns true if this call takes place in eval code */
150
isEval(): boolean;
151
/** Returns true if this call is in native V8 code */
152
isNative(): boolean;
153
/** Returns true if this is a constructor call */
154
isConstructor(): boolean;
155
}
156
```
157
158
**Important Notes:**
159
160
- **Full API Support**: `get()` returns CallSite objects with full V8 API support
161
- **Limited API Support**: `parse()` returns objects with limited method support:
162
- Reliable: `getTypeName()`, `getFunctionName()`, `getMethodName()`, `getFileName()`, `getLineNumber()`, `getColumnNumber()`, `isNative()`
163
- May return `null`: `getThis()`, `getFunction()`, `getEvalOrigin()`, `isTopLevel()`, `isEval()`, `isConstructor()`
164
165
**Usage Examples:**
166
167
```javascript
168
const stackTrace = require("stack-trace");
169
170
function analyzeStack() {
171
const trace = stackTrace.get();
172
const currentFrame = trace[0];
173
174
console.log("Function:", currentFrame.getFunctionName());
175
console.log("File:", currentFrame.getFileName());
176
console.log("Line:", currentFrame.getLineNumber());
177
console.log("Column:", currentFrame.getColumnNumber());
178
console.log("Is native:", currentFrame.isNative());
179
console.log("Is constructor:", currentFrame.isConstructor());
180
}
181
182
// Analyze parsed error stack
183
try {
184
someFunction();
185
} catch (err) {
186
const trace = stackTrace.parse(err);
187
trace.forEach(frame => {
188
if (frame.isNative()) {
189
console.log("Native call:", frame.getFunctionName());
190
} else {
191
console.log(`${frame.getFunctionName()} at ${frame.getFileName()}:${frame.getLineNumber()}`);
192
}
193
});
194
}
195
```
196
197
## Advanced Features
198
199
### Long Stack Traces Integration
200
201
Stack Trace is compatible with the `long-stack-traces` module for cross-event-loop boundary tracing.
202
203
```javascript
204
require("long-stack-traces");
205
const stackTrace = require("stack-trace");
206
207
setTimeout(() => {
208
const err = new Error("Async error");
209
const trace = stackTrace.parse(err);
210
211
// Event loop boundary markers appear as special CallSite objects
212
trace.forEach(frame => {
213
if (frame.getFileName() === "----------------------------------------") {
214
console.log("Event loop boundary detected");
215
}
216
});
217
}, 100);
218
```
219
220
### Error Handling and Edge Cases
221
222
The library handles various edge cases gracefully:
223
224
- **Missing stack property**: Returns empty array
225
- **Corrupted stack traces**: Filters out unparseable lines
226
- **Native function calls**: Properly identifies with `isNative()` returning `true`
227
- **Anonymous functions**: Handles anonymous function detection
228
- **Complex function names**: Parses object methods, nested scopes, and module boundaries
229
230
## Internal API
231
232
### _createParsedCallSite
233
234
Internal utility function for creating CallSite objects from parsed properties.
235
236
```javascript { .api }
237
/**
238
* Internal factory function for creating CallSite objects
239
* @param {Object} properties - Properties object for CallSite creation
240
* @returns {CallSite} CallSite instance with specified properties
241
*/
242
function _createParsedCallSite(properties);
243
```
244
245
**Note**: While exported, this function is primarily for internal use and testing. Normal usage should rely on `get()` and `parse()` methods.