Node.js: How to add my own non blocking task

Viewed 76

I am a java developer, who is right now trying to learn various concurrency models, currently looking at Node. As I understand following code does async io in node:-

  1.  fs = require('fs')
  2.  fs.readFile('/etc/hosts', 'utf8', function (err,data) {
  3.    if (err) {
  4.      return console.log(err);
  5.    }
  6.    console.log(data);
  7.  });

As I understand correctly, line-2, is an async call, telling node to read the file in parallel, and when done, execute callback function(appending it in the event queue?).

Does node provide any package where I can create a similar function for my own usecase, where I do an async function and place the callback for execution to event-loop?

I read that Node uses libuv package for implementing async behavior. Looks like there is a third party library on npm - npm-libuv_thread. Will it provide the mechanism I need?

Update: For the following code:-

var sleep = require('sleep');

printWithSleep();
console.log("Hello");

function printWithSleep(){
   sleep.sleep(5);
   console.log("World")
}

Node waits 5 seconds and then prints World followed by Hello, My question is - Is there any way I can make printWithSleep as async (currently its blocking)

0 Answers
Related