Node.js utility functions providing callback-to-promise conversion and error serialization for Parcel bundler
npx @tessl/cli install tessl/npm-parcel--utils@1.11.00
# Parcel Utils
1
2
Parcel Utils provides essential Node.js utility functions for the Parcel bundler ecosystem. The package offers two core utilities: callback-to-promise conversion and error serialization, designed to support asynchronous programming patterns and cross-process communication in Parcel's multi-core compilation system.
3
4
## Package Information
5
6
- **Package Name**: @parcel/utils
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install @parcel/utils`
10
- **Node.js Support**: >= 6.0.0
11
12
## Core Imports
13
14
```javascript
15
const { promisify, errorUtils } = require('@parcel/utils');
16
```
17
18
Individual imports:
19
```javascript
20
const promisify = require('@parcel/utils').promisify;
21
const errorUtils = require('@parcel/utils').errorUtils;
22
```
23
24
## Basic Usage
25
26
```javascript
27
const { promisify, errorUtils } = require('@parcel/utils');
28
const fs = require('fs');
29
30
// Convert callback-style function to promise
31
const readFile = promisify(fs.readFile);
32
33
// Use with async/await
34
async function readConfig() {
35
try {
36
const content = await readFile('config.json', 'utf8');
37
return JSON.parse(content);
38
} catch (error) {
39
// Serialize error for cross-process communication
40
const serializedError = errorUtils.errorToJson(error);
41
console.log('Error details:', serializedError);
42
43
// Later reconstruct the error
44
const reconstructedError = errorUtils.jsonToError(serializedError);
45
throw reconstructedError;
46
}
47
}
48
```
49
50
## Architecture
51
52
Parcel Utils is designed with version compatibility in mind:
53
54
- **Version Detection**: Automatically uses native async functions on Node.js 8+ or compiled versions for Node.js 6-7
55
- **Module Structure**: Two independent utilities accessed through named exports
56
- **Build System**: Uses Babel for backward compatibility with older Node.js versions
57
- **Zero Dependencies**: Pure utility library with no external runtime dependencies
58
59
## Capabilities
60
61
### Promise Conversion
62
63
Converts Node.js callback-style functions to Promise-based functions, enabling modern async/await patterns while maintaining compatibility with older callback conventions.
64
65
```javascript { .api }
66
/**
67
* Converts a callback-style function to a Promise-based function
68
* @param {Function} fn - The callback-style function to promisify
69
* @returns {Function} A new function that returns a Promise
70
*/
71
function promisify(fn: Function): Function;
72
```
73
74
The promisify function expects the callback to follow Node.js conventions:
75
- Callback is the last parameter
76
- Callback signature: `(err, ...results) => void`
77
- If `err` is truthy, the Promise rejects with that error
78
- If only one result is provided, Promise resolves with that single value
79
- If multiple results are provided, Promise resolves with an array
80
81
**Usage Examples:**
82
83
```javascript
84
const { promisify } = require('@parcel/utils');
85
const fs = require('fs');
86
87
// Promisify fs.readFile
88
const readFile = promisify(fs.readFile);
89
90
// Use with promises
91
readFile('package.json', 'utf8')
92
.then(content => console.log(JSON.parse(content)))
93
.catch(err => console.error('Error:', err));
94
95
// Use with async/await
96
async function loadPackageInfo() {
97
const content = await readFile('package.json', 'utf8');
98
return JSON.parse(content);
99
}
100
101
// Multiple results example (theoretical callback that returns multiple values)
102
const getMultipleValues = promisify((callback) => {
103
callback(null, 'first', 'second', 'third');
104
});
105
106
// Results in array: ['first', 'second', 'third']
107
const values = await getMultipleValues();
108
```
109
110
### Error Serialization
111
112
Provides robust error serialization and deserialization capabilities for converting errors to JSON format and reconstructing them. Essential for cross-process communication in Parcel's architecture.
113
114
```javascript { .api }
115
/**
116
* Converts an error to JSON-serializable format
117
* @param {string|Error|any} error - String or Error object to convert
118
* @returns {Object|undefined} Plain object representation of the error, or undefined for unsupported input types
119
*/
120
function errorToJson(error: string | Error | any): Object | undefined;
121
122
/**
123
* Reconstructs an Error object from JSON representation
124
* @param {Object} json - Plain object containing error data
125
* @returns {Error|undefined} New Error object with properties restored, or undefined if json is falsy
126
*/
127
function jsonToError(json: Object): Error | undefined;
128
```
129
130
**Error Serialization Behavior:**
131
132
For string inputs:
133
- Returns `{ message: string }`
134
135
For Error objects:
136
- Captures `message`, `stack`, and `name` properties
137
- Preserves all custom properties (useful for error codes, context, etc.)
138
- Maintains error metadata for debugging
139
140
For other input types:
141
- Returns `undefined` implicitly (no explicit return for unsupported input types)
142
143
**Error Reconstruction Behavior:**
144
145
For valid JSON objects:
146
- Creates new Error with `message` from JSON
147
- Copies all properties from JSON to the Error object
148
149
For falsy inputs (null, undefined, empty string, etc.):
150
- Returns `undefined`
151
152
**Usage Examples:**
153
154
```javascript
155
const { errorUtils } = require('@parcel/utils');
156
157
// Serialize different error types
158
const stringError = errorUtils.errorToJson('Something went wrong');
159
// Result: { message: 'Something went wrong' }
160
161
const standardError = new Error('File not found');
162
const serialized = errorUtils.errorToJson(standardError);
163
// Result: { message: 'File not found', stack: '...', name: 'Error' }
164
165
// Custom error with additional properties
166
const customError = new Error('Parse error');
167
customError.code = 'PARSE_ERROR';
168
customError.line = 42;
169
customError.column = 15;
170
171
const serializedCustom = errorUtils.errorToJson(customError);
172
// Result: { message: 'Parse error', stack: '...', name: 'Error', code: 'PARSE_ERROR', line: 42, column: 15 }
173
174
// Reconstruct errors
175
const reconstructed = errorUtils.jsonToError(serializedCustom);
176
console.log(reconstructed instanceof Error); // true
177
console.log(reconstructed.code); // 'PARSE_ERROR'
178
console.log(reconstructed.line); // 42
179
180
// Cross-process communication example
181
function sendErrorToWorker(error) {
182
const serialized = errorUtils.errorToJson(error);
183
worker.postMessage({ type: 'error', error: serialized });
184
}
185
186
function receiveErrorFromWorker(message) {
187
if (message.type === 'error') {
188
const reconstructed = errorUtils.jsonToError(message.error);
189
throw reconstructed; // Full Error object with all properties
190
}
191
}
192
```
193
194
## Types
195
196
```javascript { .api }
197
// The errorUtils object with named functions
198
interface ErrorUtils {
199
errorToJson(error: string | Error | any): Object | undefined;
200
jsonToError(json: Object): Error | undefined;
201
}
202
203
// Main module exports
204
interface ParcelUtils {
205
promisify: (fn: Function) => Function;
206
errorUtils: ErrorUtils;
207
}
208
```