0
# Node.js Integration
1
2
Utilities for bridging callback-based APIs with promises in Node.js environments, enabling seamless integration between traditional Node.js patterns and promise-based code.
3
4
## Capabilities
5
6
### Promise.denodeify
7
8
Converts Node.js-style callback functions to promise-returning functions.
9
10
```javascript { .api }
11
/**
12
* Converts callback-based function to promise-based function
13
* @param {function} fn - Function expecting callback as last parameter
14
* @param {number} [argumentCount] - Fixed number of arguments (optimization)
15
* @returns {function} Function returning promise instead of using callback
16
*/
17
Promise.denodeify(fn, argumentCount);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const Promise = require('promise');
24
const fs = require('fs');
25
26
// Convert fs.readFile to promise-based
27
const readFile = Promise.denodeify(fs.readFile);
28
29
readFile('package.json', 'utf8')
30
.then(contents => {
31
console.log('File contents:', contents);
32
})
33
.catch(error => {
34
console.error('Failed to read file:', error);
35
});
36
37
// With argument count optimization
38
const readFileOptimized = Promise.denodeify(fs.readFile, 2);
39
40
// Convert multiple functions
41
const stat = Promise.denodeify(fs.stat);
42
const writeFile = Promise.denodeify(fs.writeFile);
43
44
// Chain converted functions
45
readFile('input.txt', 'utf8')
46
.then(data => data.toUpperCase())
47
.then(transformed => writeFile('output.txt', transformed))
48
.then(() => console.log('File processed successfully'));
49
```
50
51
### Promise.nodeify
52
53
Wraps a promise-returning function to optionally accept Node.js-style callbacks.
54
55
```javascript { .api }
56
/**
57
* Wraps promise function to support optional callback parameter
58
* @param {function} fn - Function that returns a promise
59
* @returns {function} Function that accepts optional callback as last parameter
60
*/
61
Promise.nodeify(fn);
62
```
63
64
**Usage Examples:**
65
66
```javascript
67
const Promise = require('promise');
68
69
// Promise-based function
70
function fetchUserData(userId) {
71
return Promise.resolve({ id: userId, name: 'John Doe' });
72
}
73
74
// Wrap to support both promises and callbacks
75
const fetchUser = Promise.nodeify(fetchUserData);
76
77
// Use as promise
78
fetchUser(123)
79
.then(user => console.log('Promise:', user))
80
.catch(error => console.error('Promise error:', error));
81
82
// Use with callback
83
fetchUser(123, (error, user) => {
84
if (error) {
85
console.error('Callback error:', error);
86
} else {
87
console.log('Callback:', user);
88
}
89
});
90
91
// Hybrid API example
92
function createAPI() {
93
const getUserData = Promise.nodeify((id) => {
94
return fetch(`/api/users/${id}`).then(r => r.json());
95
});
96
97
return { getUserData };
98
}
99
```
100
101
### Promise.prototype.nodeify
102
103
Calls a Node.js-style callback with the promise result.
104
105
```javascript { .api }
106
/**
107
* Calls Node.js callback with promise result
108
* @param {function} [callback] - Callback function (error, result)
109
* @param {*} [ctx] - Context (this) for callback invocation
110
* @returns {Promise|void} Returns this promise if no callback, void otherwise
111
*/
112
Promise.prototype.nodeify(callback, ctx);
113
```
114
115
**Usage Examples:**
116
117
```javascript
118
const Promise = require('promise');
119
120
// Convert promise to callback style
121
function getData(callback) {
122
return fetchDataPromise()
123
.nodeify(callback);
124
}
125
126
// Usage with callback
127
getData((error, result) => {
128
if (error) {
129
console.error('Error:', error);
130
} else {
131
console.log('Result:', result);
132
}
133
});
134
135
// Usage without callback (returns promise)
136
getData()
137
.then(result => console.log('Promise result:', result))
138
.catch(error => console.error('Promise error:', error));
139
140
// With context
141
const api = {
142
name: 'MyAPI',
143
handleResult(error, data) {
144
console.log(`${this.name}:`, error || data);
145
}
146
};
147
148
fetchDataPromise().nodeify(api.handleResult, api);
149
```
150
151
## Common Patterns
152
153
### Converting Entire Modules
154
155
```javascript
156
const Promise = require('promise');
157
const fs = require('fs');
158
159
// Convert all fs functions to promise-based
160
const fsPromises = {
161
readFile: Promise.denodeify(fs.readFile),
162
writeFile: Promise.denodeify(fs.writeFile),
163
stat: Promise.denodeify(fs.stat),
164
readdir: Promise.denodeify(fs.readdir)
165
};
166
167
// Use promise-based file operations
168
async function processFiles() {
169
const files = await fsPromises.readdir('./data');
170
171
for (const file of files) {
172
const stats = await fsPromises.stat(`./data/${file}`);
173
if (stats.isFile()) {
174
const content = await fsPromises.readFile(`./data/${file}`, 'utf8');
175
// Process content...
176
}
177
}
178
}
179
```
180
181
### Dual Promise/Callback APIs
182
183
```javascript
184
const Promise = require('promise');
185
186
function createDualAPI(promiseFunction) {
187
return Promise.nodeify(promiseFunction);
188
}
189
190
// Create API that supports both patterns
191
const api = {
192
fetchUser: createDualAPI((id) => {
193
return fetch(`/users/${id}`).then(r => r.json());
194
}),
195
196
createUser: createDualAPI((userData) => {
197
return fetch('/users', {
198
method: 'POST',
199
body: JSON.stringify(userData)
200
}).then(r => r.json());
201
})
202
};
203
204
// Use as promises
205
await api.fetchUser(123);
206
207
// Use with callbacks
208
api.fetchUser(123, (err, user) => {
209
// Handle result
210
});
211
```
212
213
### Error Handling
214
215
```javascript
216
const Promise = require('promise');
217
218
// denodeify automatically handles callback errors
219
const readFile = Promise.denodeify(fs.readFile);
220
221
readFile('nonexistent.txt')
222
.catch(error => {
223
console.log(error.code); // 'ENOENT'
224
console.log(error.path); // 'nonexistent.txt'
225
});
226
227
// nodeify converts promise rejections to callback errors
228
Promise.reject(new Error('Something failed'))
229
.nodeify((err, result) => {
230
console.log(err.message); // 'Something failed'
231
console.log(result); // undefined
232
});
233
```
234
235
## Types
236
237
```javascript { .api }
238
/**
239
* Node.js-style callback signature
240
* @callback NodeCallback
241
* @param {Error|null} error - Error object or null for success
242
* @param {*} [result] - Result value (present when error is null)
243
*/
244
245
/**
246
* Function expecting Node.js-style callback as last parameter
247
* @callback NodeFunction
248
* @param {...*} args - Function arguments
249
* @param {NodeCallback} callback - Node.js callback as last parameter
250
*/
251
```