Answer the question
In order to leave comments, you need to log in
How to write a custom asynchronous module in NodeJS?
Good day, I'm studying JS and at the moment the NodeJS platform, I'm faced with the fact that I can't understand how my modules are written correctly in Nod. Frankly speaking, there is already a mess of event-ov, callback-ov, nextTickov (setTimeout) in my head.
Everywhere, as a standard of asynchrony, they give an example of the FS module:
var fs = require('fs');
fs.readFile('name.txt', function (err, data) {
});
// my custom module
function MyModule(something, callback){
if(something === 'OK'){ // Обрабатываем как-то something и передаем дальше
process.nextTick( сallback(null, something));
} else {
process.nextTick( callback('Error'));
};
};
module.exports = MyModule;
var MyModule = require('MyModule');
MyModule('something', function( err, value ) {
if(err) console.log('Вай-вай, беда!')
// ну а тут делаем еще что-то с value
});
Answer the question
In order to leave comments, you need to log in
So you can see how the same fs module is written: https://github.com/joyent/node/blob/master/lib/fs.js
How to write asynchronous functions You found the code is normal, but the asynchronous module is nonsense , here is fs module synchronous or asynchronous? After all, it has fs.readFile and fs.readFileSync. A module can contain both synchronous and asynchronous code; in general, only I/O is usually solved asynchronously in a node: working with files, network, database. All other code remains synchronous. It seems that you have not yet fully mastered the node, but already want to make your own modules. I recommend that you read the sources of good modules before that, for example, these small and well-written ones:
https://www.npmjs.com/package/mkdirp
https://www.npmjs.com/package/ncp
https://www.npmjs.com/package/colors
I advise you to go through nodeschool.io/ru and practice using modules, and then make your own. Also, be sure to master the async library: https://github.com/caolan/async and see what EventEmitter is https://nodejs.org/api/events.html And of course, read the source code of the node and other modules. Articles to google or dig on Habré should not be a problem.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question