0
# Utility Functions
1
2
Essential utility functions for object manipulation, async operations, data transformation, validation, and common programming tasks that support workflow execution and development.
3
4
## Capabilities
5
6
### Object Manipulation
7
8
Core functions for working with objects, deep copying, and data transformation.
9
10
```typescript { .api }
11
/**
12
* Check if object is empty (no enumerable properties)
13
* @param obj - Object to check
14
* @returns Boolean indicating if object is empty
15
*/
16
function isObjectEmpty(obj: object): boolean;
17
18
/**
19
* Create deep copy of object or array
20
* @param source - Source object to copy
21
* @returns Deep copied object
22
*/
23
function deepCopy<T>(source: T): T;
24
25
/**
26
* Remove circular references from object
27
* @param obj - Object to clean
28
* @returns Object without circular references
29
*/
30
function removeCircularRefs(obj: object): object;
31
32
/**
33
* Replace circular references with placeholder strings
34
* @param obj - Object to process
35
* @returns Object with circular references replaced
36
*/
37
function replaceCircularReferences(obj: object): object;
38
39
/**
40
* Check if property name is safe for object access
41
* @param property - Property name to check
42
* @returns Boolean indicating if property is safe
43
*/
44
function isSafeObjectProperty(property: string): boolean;
45
46
/**
47
* Safely set object property value
48
* @param obj - Target object
49
* @param property - Property name
50
* @param value - Value to set
51
* @returns Boolean indicating if property was set
52
*/
53
function setSafeObjectProperty(obj: object, property: string, value: any): boolean;
54
```
55
56
### JSON Operations
57
58
Safe JSON parsing and stringification with error handling.
59
60
```typescript { .api }
61
/**
62
* Safe JSON parsing with error handling
63
* @param jsonString - JSON string to parse
64
* @param fallback - Fallback value if parsing fails
65
* @returns Parsed object or fallback value
66
*/
67
function jsonParse<T = any>(jsonString: string, fallback?: T): T;
68
69
/**
70
* Safe JSON stringification with circular reference handling
71
* @param obj - Object to stringify
72
* @param space - Indentation space (optional)
73
* @returns JSON string
74
*/
75
function jsonStringify(obj: any, space?: number): string;
76
```
77
78
### Async Utilities
79
80
Asynchronous operation helpers including sleep and cancellation.
81
82
```typescript { .api }
83
/**
84
* Async sleep utility
85
* @param ms - Milliseconds to sleep
86
* @returns Promise that resolves after specified time
87
*/
88
function sleep(ms: number): Promise<void>;
89
90
/**
91
* Sleep with abort signal support
92
* @param ms - Milliseconds to sleep
93
* @param signal - Abort signal for cancellation
94
* @returns Promise that resolves after time or is cancelled
95
*/
96
function sleepWithAbort(ms: number, signal?: AbortSignal): Promise<void>;
97
98
/**
99
* Create deferred promise for async coordination
100
* @returns Deferred promise with resolve/reject methods
101
*/
102
function createDeferredPromise<T>(): IDeferredPromise<T>;
103
104
interface IDeferredPromise<T> {
105
promise: Promise<T>;
106
resolve: (value: T | PromiseLike<T>) => void;
107
reject: (reason?: any) => void;
108
}
109
```
110
111
### String and Encoding Utilities
112
113
String manipulation and encoding/decoding functions.
114
115
```typescript { .api }
116
/**
117
* Base64 decode to UTF-8 string
118
* @param str - Base64 encoded string
119
* @returns Decoded UTF-8 string
120
*/
121
function base64DecodeUTF8(str: string): string;
122
123
/**
124
* Generate random string of specified length
125
* @param length - Desired string length
126
* @param charset - Character set to use (optional)
127
* @returns Random string
128
*/
129
function randomString(length: number, charset?: string): string;
130
131
/**
132
* Generate random integer between min and max (inclusive)
133
* @param min - Minimum value
134
* @param max - Maximum value
135
* @returns Random integer
136
*/
137
function randomInt(min: number, max: number): number;
138
```
139
140
### File and MIME Type Utilities
141
142
File type detection and MIME type handling.
143
144
```typescript { .api }
145
/**
146
* Get file type from MIME type
147
* @param mimeType - MIME type string
148
* @returns File type category
149
*/
150
function fileTypeFromMimeType(mimeType: string): BinaryFileType;
151
152
type BinaryFileType = 'text' | 'json' | 'image' | 'audio' | 'video' | 'pdf' | 'html';
153
```
154
155
### Validation and Assertion
156
157
Validation helpers and assertion utilities.
158
159
```typescript { .api }
160
/**
161
* Assert condition is true or throw error
162
* @param condition - Condition to assert
163
* @param message - Error message if assertion fails
164
* @throws AssertionError if condition is false
165
*/
166
function assert(condition: any, message?: string): asserts condition;
167
168
/**
169
* Validate and normalize email address
170
* @param email - Email address to validate
171
* @returns Normalized email or null if invalid
172
*/
173
function normalizeEmail(email: string): string | null;
174
175
/**
176
* Validate URL format
177
* @param url - URL string to validate
178
* @returns Boolean indicating if URL is valid
179
*/
180
function isValidUrl(url: string): boolean;
181
```
182
183
### Display Options and UI Utilities
184
185
Utilities for managing node display options and UI configurations.
186
187
```typescript { .api }
188
/**
189
* Update display options for node properties
190
* @param displayOptions - Current display options
191
* @param properties - Properties to update options for
192
* @returns Updated display options
193
*/
194
function updateDisplayOptions(
195
displayOptions: IDisplayOptions,
196
properties: INodeProperties[]
197
): IDisplayOptions;
198
199
interface IDisplayOptions {
200
show?: { [key: string]: any[] };
201
hide?: { [key: string]: any[] };
202
}
203
204
/**
205
* Check if property should be displayed based on conditions
206
* @param property - Node property definition
207
* @param currentValues - Current parameter values
208
* @returns Boolean indicating if property should be shown
209
*/
210
function shouldDisplayProperty(
211
property: INodeProperties,
212
currentValues: INodeParameters
213
): boolean;
214
```
215
216
### Data Transformation Utilities
217
218
Helper functions for common data transformations and formatting.
219
220
```typescript { .api }
221
/**
222
* Flatten nested object into dot notation
223
* @param obj - Object to flatten
224
* @param prefix - Key prefix (optional)
225
* @returns Flattened object
226
*/
227
function flattenObject(obj: object, prefix?: string): IDataObject;
228
229
/**
230
* Unflatten dot notation object back to nested structure
231
* @param obj - Flattened object
232
* @returns Nested object structure
233
*/
234
function unflattenObject(obj: IDataObject): object;
235
236
/**
237
* Convert object keys to camelCase
238
* @param obj - Object to convert
239
* @returns Object with camelCase keys
240
*/
241
function camelCaseKeys(obj: object): object;
242
243
/**
244
* Convert object keys to snake_case
245
* @param obj - Object to convert
246
* @returns Object with snake_case keys
247
*/
248
function snakeCaseKeys(obj: object): object;
249
250
/**
251
* Pick specified properties from object
252
* @param obj - Source object
253
* @param keys - Keys to pick
254
* @returns Object with only specified keys
255
*/
256
function pick<T extends object, K extends keyof T>(
257
obj: T,
258
keys: K[]
259
): Pick<T, K>;
260
261
/**
262
* Omit specified properties from object
263
* @param obj - Source object
264
* @param keys - Keys to omit
265
* @returns Object without specified keys
266
*/
267
function omit<T extends object, K extends keyof T>(
268
obj: T,
269
keys: K[]
270
): Omit<T, K>;
271
```
272
273
### Array Utilities
274
275
Utility functions for array manipulation and processing.
276
277
```typescript { .api }
278
/**
279
* Chunk array into smaller arrays of specified size
280
* @param array - Array to chunk
281
* @param size - Chunk size
282
* @returns Array of chunks
283
*/
284
function chunk<T>(array: T[], size: number): T[][];
285
286
/**
287
* Remove duplicate values from array
288
* @param array - Array to deduplicate
289
* @param keyFn - Optional key function for complex objects
290
* @returns Array with unique values
291
*/
292
function unique<T>(array: T[], keyFn?: (item: T) => any): T[];
293
294
/**
295
* Flatten nested arrays
296
* @param array - Array to flatten
297
* @param depth - Maximum depth to flatten (default: 1)
298
* @returns Flattened array
299
*/
300
function flatten<T>(array: any[], depth?: number): T[];
301
302
/**
303
* Group array elements by key function
304
* @param array - Array to group
305
* @param keyFn - Function to determine grouping key
306
* @returns Object with grouped elements
307
*/
308
function groupBy<T, K extends string | number | symbol>(
309
array: T[],
310
keyFn: (item: T) => K
311
): Record<K, T[]>;
312
```
313
314
**Usage Examples:**
315
316
```typescript
317
import {
318
deepCopy,
319
isObjectEmpty,
320
jsonParse,
321
sleep,
322
randomString,
323
assert,
324
updateDisplayOptions,
325
flattenObject,
326
chunk,
327
unique
328
} from "n8n-workflow";
329
330
// Object manipulation
331
const originalData = {
332
user: { name: "John", details: { age: 30, city: "NYC" } },
333
items: [1, 2, 3]
334
};
335
336
const copied = deepCopy(originalData);
337
console.log('Deep copy created');
338
339
const isEmpty = isObjectEmpty({});
340
console.log('Empty object check:', isEmpty); // true
341
342
// Safe JSON operations
343
const jsonData = jsonParse('{"name": "John", "age": 30}', {});
344
console.log('Parsed JSON:', jsonData);
345
346
const invalidJson = jsonParse('invalid json', { error: 'parsing failed' });
347
console.log('Invalid JSON fallback:', invalidJson);
348
349
// Async utilities
350
async function asyncExample() {
351
console.log('Starting operation...');
352
await sleep(1000); // Wait 1 second
353
console.log('Operation completed');
354
355
// With abort signal
356
const controller = new AbortController();
357
setTimeout(() => controller.abort(), 500);
358
359
try {
360
await sleepWithAbort(1000, controller.signal);
361
} catch (error) {
362
console.log('Sleep was aborted');
363
}
364
}
365
366
// String and random utilities
367
const randomId = randomString(16);
368
console.log('Random ID:', randomId);
369
370
const randomNumber = randomInt(1, 100);
371
console.log('Random number between 1-100:', randomNumber);
372
373
// Assertion
374
try {
375
assert(typeof randomNumber === 'number', 'Random number should be numeric');
376
console.log('Assertion passed');
377
} catch (error) {
378
console.log('Assertion failed:', error.message);
379
}
380
381
// Display options
382
const displayOptions = updateDisplayOptions(
383
{ show: { operation: ['create', 'update'] } },
384
[
385
{ displayName: 'Name', name: 'name', type: 'string' },
386
{ displayName: 'Email', name: 'email', type: 'string' }
387
]
388
);
389
390
// Data transformation
391
const nestedObject = {
392
user: {
393
profile: {
394
name: 'John',
395
contact: {
396
email: 'john@example.com'
397
}
398
}
399
}
400
};
401
402
const flattened = flattenObject(nestedObject);
403
console.log('Flattened:', flattened);
404
// Result: { 'user.profile.name': 'John', 'user.profile.contact.email': '...' }
405
406
// Array utilities
407
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
408
const chunks = chunk(numbers, 3);
409
console.log('Chunked array:', chunks); // [[1,2,3], [4,5,6], [7,8,9]]
410
411
const duplicates = [1, 2, 2, 3, 3, 3, 4];
412
const uniqueValues = unique(duplicates);
413
console.log('Unique values:', uniqueValues); // [1, 2, 3, 4]
414
415
// Complex object operations
416
const userProfiles = [
417
{ id: 1, name: 'John', department: 'IT' },
418
{ id: 2, name: 'Jane', department: 'HR' },
419
{ id: 3, name: 'Bob', department: 'IT' }
420
];
421
422
const uniqueUsers = unique(userProfiles, user => user.department);
423
console.log('Unique by department:', uniqueUsers);
424
425
// Circular reference handling
426
const circular: any = { name: 'test' };
427
circular.self = circular;
428
429
const cleaned = removeCircularRefs(circular);
430
console.log('Cleaned object:', cleaned);
431
432
const replaced = replaceCircularReferences(circular);
433
console.log('Replaced circular refs:', replaced);
434
```