Rectangle 27 2

I'm unclear what the call function is doing here, apparently calling EventEmitter's constructor?

super

After setting the prototype it seems to work as expected.

Indeed, you need to let your Jobs inherit from EventEmitter. However, you really should not use new here, but rather

Job.prototype = Object.create(EventEmitter.prototype);

@DevAlien: Much more correct? Not really - it's what util.inherits does internally. I admit that it might be the more "node" way of inheritance, while Object.create is just idiomatic pure JavaScript.

javascript - Event emitter constructor - Stack Overflow

javascript node.js
Rectangle 27 85

Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.

The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).

By removing them from the core node.js, it created possibility of building up modules with different implementations of promises that can sit on top of the core. Some of these are node-promise and futures.

javascript - Understanding promises in node.js - Stack Overflow

javascript node.js promise
Rectangle 27 85

Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.

The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).

By removing them from the core node.js, it created possibility of building up modules with different implementations of promises that can sit on top of the core. Some of these are node-promise and futures.

javascript - Understanding promises in node.js - Stack Overflow

javascript node.js promise
Rectangle 27 77

The Node.js event loop runs under a single thread, this means the application code you write is evaluated on a single thread. Nodejs itself uses many threads underneath through libuv, but you never have to deal with with those when writing nodejs code.

Every call that involves I/O call requires you to register a callback. This call also returns immediately, this allows you to do multiple IO operations in parallel without using threads in your application code. As soon as an I/O operation is completed it's callback will be pushed on the event loop. It will be executed as soon as all the other callbacks that where pushed on the event loop before it are executed.

There are a few methods to do basic manipulation of how callbacks are added to the event loop. Usually you shouldn't need these, but every now and then they can be useful.

At no point will there ever be two true parallel paths of execution, so all operations are inherently thread safe. There usually will be several asynchronous concurrent paths of execution that are being managed by the event loop.

Because of the event loop, node doesn't have to start a new thread for every incoming tcp connection. This allows node to service hundreds of thousands of requests concurrently , as long as you aren't calculating the first 1000 prime numbers for each request.

This also means it's important to not do CPU intensive operations, as these will keep a lock on the event loop and prevent other asynchronous paths of execution from continuing. It's also important to not use the sync variant of all the I/O methods, as these will keep a lock on the event loop as well.

If you want to do CPU heavy things you should ether delegate it to a different process that can execute the CPU bound operation more efficiently or you could write it as a node native add on.

In order to manage writing many callbacks you will probably want to use a control flow library. I believe this is currently the most popular callback based library:

I've used callbacks and they pretty much drove me crazy, I've had much better experience using Promises, bluebird is a very popular and fast promise library:

I've found this to be a pretty sensitive topic in the node community (callbacks vs promises), so by all means, use what you feel will work best for you personally. A good control flow library should also give you async stack traces, this is really important for debugging.

The Node.js process will finish when the last callback in the event loop finishes it's path of execution and doesn't register any other callbacks.

This is not a complete explanation, I advice you to check out the following thread, it's pretty up to date:

@WillemD'haeseleer please! Explain me the next your phrase "The Node.js event loop runs under a single thread.. Nodejs itself uses many threads underneath trough libuv". I know how works js-loop in browser, but I do not understand what is the role of multi-threaded libuv.

threads are used by libuv for all sorts of stuff that required CPU bound operations. If you want to better understand that I recommend you read up on libuv here nikhilm.github.io/uvbook/threads.html, and here: nikhilm.github.io/uvbook/basics.html

How is nodejs able to manage concurrent connections? Does it do with a significant lag? I hear that it could support tens of thousands of concurrent connections, more than apache. Could you explain how all this is possible, provided nodejs handles/processes HTTP requests on a single thread?

"Every call that involves I/O call requires you to register a callback." That is not accurate. Calls like readFileSync, writeFileSync, etc do not require callbacks for I/O.

Node.js Event loop - Stack Overflow

node.js loops events
Rectangle 27 77

The Node.js event loop runs under a single thread, this means the application code you write is evaluated on a single thread. Nodejs itself uses many threads underneath through libuv, but you never have to deal with with those when writing nodejs code.

Every call that involves I/O call requires you to register a callback. This call also returns immediately, this allows you to do multiple IO operations in parallel without using threads in your application code. As soon as an I/O operation is completed it's callback will be pushed on the event loop. It will be executed as soon as all the other callbacks that where pushed on the event loop before it are executed.

There are a few methods to do basic manipulation of how callbacks are added to the event loop. Usually you shouldn't need these, but every now and then they can be useful.

At no point will there ever be two true parallel paths of execution, so all operations are inherently thread safe. There usually will be several asynchronous concurrent paths of execution that are being managed by the event loop.

Because of the event loop, node doesn't have to start a new thread for every incoming tcp connection. This allows node to service hundreds of thousands of requests concurrently , as long as you aren't calculating the first 1000 prime numbers for each request.

This also means it's important to not do CPU intensive operations, as these will keep a lock on the event loop and prevent other asynchronous paths of execution from continuing. It's also important to not use the sync variant of all the I/O methods, as these will keep a lock on the event loop as well.

If you want to do CPU heavy things you should ether delegate it to a different process that can execute the CPU bound operation more efficiently or you could write it as a node native add on.

In order to manage writing many callbacks you will probably want to use a control flow library. I believe this is currently the most popular callback based library:

I've used callbacks and they pretty much drove me crazy, I've had much better experience using Promises, bluebird is a very popular and fast promise library:

I've found this to be a pretty sensitive topic in the node community (callbacks vs promises), so by all means, use what you feel will work best for you personally. A good control flow library should also give you async stack traces, this is really important for debugging.

The Node.js process will finish when the last callback in the event loop finishes it's path of execution and doesn't register any other callbacks.

This is not a complete explanation, I advice you to check out the following thread, it's pretty up to date:

@WillemD'haeseleer please! Explain me the next your phrase "The Node.js event loop runs under a single thread.. Nodejs itself uses many threads underneath trough libuv". I know how works js-loop in browser, but I do not understand what is the role of multi-threaded libuv.

threads are used by libuv for all sorts of stuff that required CPU bound operations. If you want to better understand that I recommend you read up on libuv here nikhilm.github.io/uvbook/threads.html, and here: nikhilm.github.io/uvbook/basics.html

How is nodejs able to manage concurrent connections? Does it do with a significant lag? I hear that it could support tens of thousands of concurrent connections, more than apache. Could you explain how all this is possible, provided nodejs handles/processes HTTP requests on a single thread?

"Every call that involves I/O call requires you to register a callback." That is not accurate. Calls like readFileSync, writeFileSync, etc do not require callbacks for I/O.

Node.js Event loop - Stack Overflow

node.js loops events
Rectangle 27 1

I think, through the comment thread, I've identified your issue. REQ/REP has a strict synchronous message order guarantee... You must receive-send-receive-send-etc. REQ must start with send and REP must start with receive. So, you're only processing one message at a time because the socket types you've chosen enforce that.

If you were using a different, non-event-driven language, you'd likely get an error telling you what you'd done wrong when you tried to send or receive twice in a row, but node lets you do it and just queues the subsequent messages until it's their turn in the message order.

You want to change REQ/REP to DEALER/ROUTER and it'll work the way you expect. You'll have to change your logic slightly for the ROUTER socket to get it to send appropriately, but everything else should work the same.

Rough example code, using the relevant portions of the posted gist:

var zmqResponder = zmq.socket('router');

zmqResponder.on('message', function (msg, data) {
    var peer_id = msg[0];
    var parsed = JSON.parse(msg[1]);
    switch (parsed.event) {
        case 'create':
            // build parsedResponse, then...
            zmqResponder.send([peer_id, JSON.stringify(parsedResponse)]);
            break;
    }
});

zmqResponder.bind('tcp://*:5668', function (err) {
    if (err) {
        logging.error(err);
    } else {
        logging.info("ZMQ awaiting orders on port 5668");
    }
});

... you need to grab the peer_id (or whatever you want to call it, in ZMQ nomenclature it's the socket ID of the socket you're sending from, think of it as an "address" of sorts) from the first frame of the message you receive, and then use send it as the first frame of the message you send back.

By the way, I just noticed in your gist you are both connect()-ing and bind()-ing on the same socket (zmq.js lines 52 & 143, respectively). Don't do that. Inferring from other clues, you just want to bind() on this side of the process.

Any chance you have some example code? I'm having a hard time figuring out this model with the examples on zmq docs. Trying to get my second gist working.

Glad we could figure out what was going wrong :)

javascript - NodeJS Event Emitter Blocking Issue - Stack Overflow

javascript node.js zeromq
Rectangle 27 18

The Node.js event loop runs under a single thread. Every I/O call requires you to register a callback. Every I/O call also returns immediately, this allows you to do multiple IO operations in parallel without using threads.

I would like to start explaining with this above quote, which is one of the common misunderstandings of node js framework that I am seeing everywhere.

Node.js does not magically handle all those asynchronous calls with just one thread and still keep that thread unblocked. It internally uses google's V8 engine and a library called libuv(written in c++) that enables it to delegate some potential asynchronous work to other worker threads (kind of like a pool of threads waiting there for any work to be delegated from the master node thread). Then later when those threads finish their execution they call their callbacks and that is how the event loop is aware of the fact that the execution of a worker thread is completed.

The main point and advantage of nodejs is that you will never need to care about those internal threads and they will stay away from your code!. All the nasty sync stuff that should normally happen in multi threaded environments will be abstracted out by nodejs framework and you can happily work on your single thread (main node thread) in a more programmer friendly environment (while benefiting from all the performance enhancements of multiple threads).

I am saying the event loop runs single threaded, not the entirety of node. I augmented my answer to point out that you don't have to deal with threads in your application code specifically. Thx for the feedback.

Node.js Event loop - Stack Overflow

node.js loops events
Rectangle 27 18

The Node.js event loop runs under a single thread. Every I/O call requires you to register a callback. Every I/O call also returns immediately, this allows you to do multiple IO operations in parallel without using threads.

I would like to start explaining with this above quote, which is one of the common misunderstandings of node js framework that I am seeing everywhere.

Node.js does not magically handle all those asynchronous calls with just one thread and still keep that thread unblocked. It internally uses google's V8 engine and a library called libuv(written in c++) that enables it to delegate some potential asynchronous work to other worker threads (kind of like a pool of threads waiting there for any work to be delegated from the master node thread). Then later when those threads finish their execution they call their callbacks and that is how the event loop is aware of the fact that the execution of a worker thread is completed.

The main point and advantage of nodejs is that you will never need to care about those internal threads and they will stay away from your code!. All the nasty sync stuff that should normally happen in multi threaded environments will be abstracted out by nodejs framework and you can happily work on your single thread (main node thread) in a more programmer friendly environment (while benefiting from all the performance enhancements of multiple threads).

I am saying the event loop runs single threaded, not the entirety of node. I augmented my answer to point out that you don't have to deal with threads in your application code specifically. Thx for the feedback.

Node.js Event loop - Stack Overflow

node.js loops events
Rectangle 27 119

What Node.js comes with

The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).

http / https createServer which simply takes a callback(req,res) e.g.

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework

app
  • Can handle a request and return a response. This is because you basically get this function
.use

Because of 1.) you can do the following :

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

Combine with 2.) and you get:

Connect provides a utility function to register itself with http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
var connect = require('connect');

// Create a connect dispatcher and register with http
var app = connect()
          .listen(3000);
console.log('server running on port 3000');

It's still your good old http.createServer with a plugin framework on top.

ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:

  • Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
listen

In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.

The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.

  • Use http.createServer if you are creating something like connect / expressjs from scratch.
  • Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of http.createServer
  • Use ExpressJS if you are authoring websites.

These might have been true as some point in time, but wrong now:

that inherits an extended version of http.Server

Wrong. It doesn't extend it and as you have seen ... uses it

Express does to Connect what Connect does to the http module

you say gives you the ability to handle a request and return a response but people say that Express is really the web server...I'm confused. Wouldn't sending a response back need web server capability (like Express)?

good stuff, thanks! very helpful...especially not knowing that connect really is what provides the routing, and express just inherits that, it isn't the sole/source provider of routing. And the use cases at the end are helpful because I assumed I'd have to use connect AND express but really all you need to use is express for web apps so this cleared a huge thing up for me. You don't install both, you install one or the other!

What is Node.js' Connect, Express and "middleware"? - Stack Overflow

node.js middleware
Rectangle 27 216

The "good node.js /event driven" way of doing this is to not wait.

Like almost everything else when working with event driven systems like node, your function should accept a callback parameter that will be invoked when then computation is complete. The caller should not wait for the value to be "returned" in the normal sense, but rather send the routine that will handle the resulting value:

function(query, callback) {
  myApi.exec('SomeCommand', function(response) {
    // other stuff here...
    // bla bla..
    callback(response); // this will "return" your value to the original caller
  });
}
var returnValue = myFunction(query);
myFunction(query, function(returnValue) {
  // use the return value here instead of like a regular (non-evented) return value
});

Ok great. What about if myApi.exec never called the callback? How would i make it so that the callback gets called after say 10 seconds with an error value saying it timed our or something?

Or better yet (added a check so the callback cant be invoked twice): jsfiddle.net/LdaFw/1

It is clear non-blocking is the standard in node/js, however there are certainly times when blocking is desired (e.g. blocking on stdin). Even node has "blocking" methods (see all the fs sync* methods). As such, I think this is still a valid question. Is there a nice way to achieve blocking in node aside from busy waiting?

A late answer to the comment by @nategood: I can think of a couple of ways; too much to explain in this comment, but google them. Remember that Node is not made to be blocked, so these are not perfect. Think of them as suggestions. Anyway, here goes: (1) Use C to implement your function and publish it to NPM in order to use it. That's what the sync methods do. (2) Use fibers, github.com/laverdet/node-fibers, (3) Use promises, for example the Q-library, (4) Use a thin layer on top of javascript, that looks blocking, but compiles to async, like maxtaco.github.com/coffee-script

It is so frustrating when people answer a question with "you shouldn't do that." If one wants to be helpful and answer a question, that is a stand up thing to do. But telling me unequivocally that I shouldn't do something is just unfriendly. There are a million different reasons why someone would want to call a routine synchronously or asynchronously. This was a question about how to do it. If you provide helpful advice about the nature of the api while providing the answer, that is helpful, but if you don't provide an answer, why bother replying. (I guess I should really head my own advice.)

javascript - How to make a function wait until a callback has been cal...

javascript multithreading callback node.js
Rectangle 27 216

The "good node.js /event driven" way of doing this is to not wait.

Like almost everything else when working with event driven systems like node, your function should accept a callback parameter that will be invoked when then computation is complete. The caller should not wait for the value to be "returned" in the normal sense, but rather send the routine that will handle the resulting value:

function(query, callback) {
  myApi.exec('SomeCommand', function(response) {
    // other stuff here...
    // bla bla..
    callback(response); // this will "return" your value to the original caller
  });
}
var returnValue = myFunction(query);
myFunction(query, function(returnValue) {
  // use the return value here instead of like a regular (non-evented) return value
});

Ok great. What about if myApi.exec never called the callback? How would i make it so that the callback gets called after say 10 seconds with an error value saying it timed our or something?

Or better yet (added a check so the callback cant be invoked twice): jsfiddle.net/LdaFw/1

It is clear non-blocking is the standard in node/js, however there are certainly times when blocking is desired (e.g. blocking on stdin). Even node has "blocking" methods (see all the fs sync* methods). As such, I think this is still a valid question. Is there a nice way to achieve blocking in node aside from busy waiting?

A late answer to the comment by @nategood: I can think of a couple of ways; too much to explain in this comment, but google them. Remember that Node is not made to be blocked, so these are not perfect. Think of them as suggestions. Anyway, here goes: (1) Use C to implement your function and publish it to NPM in order to use it. That's what the sync methods do. (2) Use fibers, github.com/laverdet/node-fibers, (3) Use promises, for example the Q-library, (4) Use a thin layer on top of javascript, that looks blocking, but compiles to async, like maxtaco.github.com/coffee-script

It is so frustrating when people answer a question with "you shouldn't do that." If one wants to be helpful and answer a question, that is a stand up thing to do. But telling me unequivocally that I shouldn't do something is just unfriendly. There are a million different reasons why someone would want to call a routine synchronously or asynchronously. This was a question about how to do it. If you provide helpful advice about the nature of the api while providing the answer, that is helpful, but if you don't provide an answer, why bother replying. (I guess I should really head my own advice.)

javascript - How to make a function wait until a callback has been cal...

javascript multithreading callback node.js
Rectangle 27 116

What Node.js comes with

The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).

http / https createServer which simply takes a callback(req,res) e.g.

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework

app
  • Can handle a request and return a response. This is because you basically get this function
.use

Because of 1.) you can do the following :

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

Combine with 2.) and you get:

Connect provides a utility function to register itself with http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
var connect = require('connect');

// Create a connect dispatcher and register with http
var app = connect()
          .listen(3000);
console.log('server running on port 3000');

It's still your good old http.createServer with a plugin framework on top.

ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:

  • Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
listen

In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.

The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.

  • Use http.createServer if you are creating something like connect / expressjs from scratch.
  • Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of http.createServer
  • Use ExpressJS if you are authoring websites.

These might have been true as some point in time, but wrong now:

that inherits an extended version of http.Server

Wrong. It doesn't extend it and as you have seen ... uses it

Express does to Connect what Connect does to the http module

you say gives you the ability to handle a request and return a response but people say that Express is really the web server...I'm confused. Wouldn't sending a response back need web server capability (like Express)?

good stuff, thanks! very helpful...especially not knowing that connect really is what provides the routing, and express just inherits that, it isn't the sole/source provider of routing. And the use cases at the end are helpful because I assumed I'd have to use connect AND express but really all you need to use is express for web apps so this cleared a huge thing up for me. You don't install both, you install one or the other!

What is Node.js' Connect, Express and "middleware"? - Stack Overflow

node.js middleware
Rectangle 27 1294

Call the global process object's exit method:

process.exit()

Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

To exit with a 'failure' code:

process.exit(1);

The shell that executed node should see the exit code as 1.

Just want to add something. If you are handling a request, you should also end() the request as well. Otherwise, it'll just hang.

@pixelfreak, exit isn't misleading at all. You are confused about how Node works. Think of Node as the server itself. It isn't just fired up as needed, like PHP is within a web server like Apache. Node doesn't even have to have anything to do with web servers at all! It's just a host for some JavaScript, with some nifty built-in libraries for doing useful things.

@Brad And PHP is a general purpose language. No need to run it with mod_php or use Apache. You can reimplement an httpd in PHP like node does if you really want or use a more sane/standardized approach like FastCGI just like you can in node.

How to exit in Node.js - Stack Overflow

node.js
Rectangle 27 1284

Call the global process object's exit method:

process.exit()

Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

To exit with a 'failure' code:

process.exit(1);

The shell that executed node should see the exit code as 1.

Just want to add something. If you are handling a request, you should also end() the request as well. Otherwise, it'll just hang.

@pixelfreak, exit isn't misleading at all. You are confused about how Node works. Think of Node as the server itself. It isn't just fired up as needed, like PHP is within a web server like Apache. Node doesn't even have to have anything to do with web servers at all! It's just a host for some JavaScript, with some nifty built-in libraries for doing useful things.

@Brad And PHP is a general purpose language. No need to run it with mod_php or use Apache. You can reimplement an httpd in PHP like node does if you really want or use a more sane/standardized approach like FastCGI just like you can in node.

How to exit in Node.js - Stack Overflow

node.js
Rectangle 27 217

Step 2 - Install the version of node.js you need

The Current/Stable "LTS" version of node is 6.11.3 (2017-09-07) see: nodejs.org for latest.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.3/install.sh | bash

Once you've got NVM you can install a specific version of Node.js using the nvm command:

nvm install v6.11.3
nvm

You should expect to see something like this in your terminal:

Now using node v6.11.3
sudo

Review of the node mailing list indicates that using NVM (Node Version Manager) is the preferred way to manage your nodejs versioning/upgrading. see: github.com/creationix/nvm

NVM by Tim Caswell (& friends) is "better" than N from visionmedia (TJ Holowaychuk) github.com/visionmedia/n because the verbose commands mean is much easier to keep track of what you are doing in your Terminal/SSH Log. Its also faster, saves kittens by not requiring sudo and is used by the team at liftsecurity.io the node.js security experts!

Also worth noting: NVM has almost thee times as many GitHub Stars as N (8742 vs 3098) that's usually - but not always - a sign of a better module... feel free to correct if you have evidence of otherwise ...

I need version 0.8 to install grunt-contrib and nvm seems to provide only up to 0.6. This seems to rule out nvm as an option for me.

None of them are supported in Windows. NVM suggests nvmw and nvm-windows that are "neither supported nor developed by" NVM and I havent testsed out yet. @nelsonic your answer is awesome

I have used nvm-windows for quite a while now. Seems pretty solid.

upgrade - Upgrading Node.js to latest version - Stack Overflow

node.js upgrade
Rectangle 27 217

Step 2 - Install the version of node.js you need

The Current/Stable "LTS" version of node is 6.11.3 (2017-09-07) see: nodejs.org for latest.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.3/install.sh | bash

Once you've got NVM you can install a specific version of Node.js using the nvm command:

nvm install v6.11.3
nvm

You should expect to see something like this in your terminal:

Now using node v6.11.3
sudo

Review of the node mailing list indicates that using NVM (Node Version Manager) is the preferred way to manage your nodejs versioning/upgrading. see: github.com/creationix/nvm

NVM by Tim Caswell (& friends) is "better" than N from visionmedia (TJ Holowaychuk) github.com/visionmedia/n because the verbose commands mean is much easier to keep track of what you are doing in your Terminal/SSH Log. Its also faster, saves kittens by not requiring sudo and is used by the team at liftsecurity.io the node.js security experts!

Also worth noting: NVM has almost thee times as many GitHub Stars as N (8742 vs 3098) that's usually - but not always - a sign of a better module... feel free to correct if you have evidence of otherwise ...

I need version 0.8 to install grunt-contrib and nvm seems to provide only up to 0.6. This seems to rule out nvm as an option for me.

None of them are supported in Windows. NVM suggests nvmw and nvm-windows that are "neither supported nor developed by" NVM and I havent testsed out yet. @nelsonic your answer is awesome

I have used nvm-windows for quite a while now. Seems pretty solid.

upgrade - Upgrading Node.js to latest version - Stack Overflow

node.js upgrade
Rectangle 27 673

I used the following instructions to upgrade from Node.js version 0.10.6 to 0.10.21 on a Mac.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Alternatively pick a specific version and install like this:

sudo n 0.8.20

For production environments you might want to pay attention to version numbering and be picky about odd/even numbers.

This four years old post still receives up-votes so I'm guessing it still works for many people. However, Mr. Walsh himself recommended to update Node.js just using nvm instead.

So here's what you might want to do today:

Find out which version of Node.js you are using:

node --version

Find out which versions of Node.js you may have installed and which one of those you're currently using:

nvm ls

List all versions of Node.js available for installation:

nvm ls-remote

Apparently for Windows the command would be rather like this:

nvm ls available

Assuming you would pick Node.js v8.1.0 for installation you'd type the following to install that version:

nvm install 8.1.0

You are then free to choose between installed versions of Node.js. So if you would need to use an older version like v4.2.0 you would set it as the active version like this:

nvm use 4.2

Does not work on Windows.

You should credit your source - your answer is quoted from David Walsh's blog: davidwalsh.name/upgrade-nodejs. It should also be noted that this method has major caveats, some rather destructive, as seen in the comments on the original blog post.

Unfortunately that din't worked for me.. was doing exact as described on a Linux machine - 'node -v' before and after showed 'v0.10.5'

One more step. Close and re-open terminal or if using ssh, exit and log back in to see new node-v

How do I update Node.js? - Stack Overflow

node.js
Rectangle 27 669

I used the following instructions to upgrade from Node.js version 0.10.6 to 0.10.21 on a Mac.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Alternatively pick a specific version and install like this:

sudo n 0.8.20

For production environments you might want to pay attention to version numbering and be picky about odd/even numbers.

This four years old post still receives up-votes so I'm guessing it still works for many people. However, Mr. Walsh himself recommended to update Node.js just using nvm instead.

So here's what you might want to do today:

Find out which version of Node.js you are using:

node --version

Find out which versions of Node.js you may have installed and which one of those you're currently using:

nvm ls

List all versions of Node.js available for installation:

nvm ls-remote

Apparently for Windows the command would be rather like this:

nvm ls available

Assuming you would pick Node.js v8.1.0 for installation you'd type the following to install that version:

nvm install 8.1.0

You are then free to choose between installed versions of Node.js. So if you would need to use an older version like v4.2.0 you would set it as the active version like this:

nvm use 4.2

Does not work on Windows.

You should credit your source - your answer is quoted from David Walsh's blog: davidwalsh.name/upgrade-nodejs. It should also be noted that this method has major caveats, some rather destructive, as seen in the comments on the original blog post.

Unfortunately that din't worked for me.. was doing exact as described on a Linux machine - 'node -v' before and after showed 'v0.10.5'

One more step. Close and re-open terminal or if using ssh, exit and log back in to see new node-v

How do I update Node.js? - Stack Overflow

node.js
Rectangle 27 498

For even newer version of Node.js (v8.1.4), the events and calls are similar or identical to older versions, but it's encouraged to use the standard newer language features. Examples:

child_process.exec
const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

You can also use it with Promises:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function ls() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
ls();

If you wish to receive the data gradually in chunks (output as a stream), use child_process.spawn:

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
  // data from standard output is here as buffers
});

// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Both of these functions have a synchronous counterpart. An example for child_process.execSync:

const { execSync } = require('child_process');
// stderr is sent to stdout of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');

As well as child_process.spawnSync:

const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);

console.log('error', child.error);
console.log('stdout ', child.stderr);
console.log('stderr ', child.stderr);

Note: The following code is still functional, but is primarily targeted at users of ES5 and before.

The module for spawning child processes with Node.js is well documented in the documentation (v5.0.0). To execute a command and fetch its complete output as a buffer, use child_process.exec:

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

If you need to use handle process I/O with streams, such as when you are expecting large amounts of output, use child_process.spawn:

var spawn = require('child_process').spawn;
var child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

// or if you want to send output elsewhere
child.stdout.pipe(dest);

If you are executing a file rather than a command, you might want to use child_process.execFile, which parameters which are almost identical to spawn, but has a fourth callback parameter like exec for retrieving output buffers. That might look a bit like this:

var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
  // command output is in stdout
});

As of v0.11.12, Node now supports synchronous spawn and exec. All of the methods described above are asynchronous, and have a synchronous counterpart. Documentation for them can be found here. While they are useful for scripting, do note that unlike the methods used to spawn child processes asynchronously, the synchronous methods do not return an instance of ChildProcess.

THANK YOU. This was driving me nuts. Sometimes it helps to just have the obvious solution pointed out so we noobs (to node) can learn and run with it.

Note : require('child_process').execFile() will be of interest for people who need to run a file rather than a system-wide known command like prince here.

child.pipe(dest)
child.stdout.pipe(dest)
child.stderr.pipe(dest)
child.stdout.pipe(process.stdout)
child.stderr.pipe(process.stderr)

What if I don't want to put everything into a file, but I want to execute more than one command? Maybe like echo "hello" and echo "world".

is this the standard way to do this ? i mean how all the wrapper are written in nodejs ? i mean let's say for gearman,rabbitmq etc. which require to run the command but they also have some wrapper as well but i can't find any of this code in their library code

javascript - Execute a command line binary with Node.js - Stack Overfl...

javascript ruby node.js command-line-interface
Rectangle 27 75

As the comment above that code says, it will make Master inherit from EventEmitter.prototype, so you can use instances of that 'class' to emit and listen to events.

masterInstance = new Master();

masterInstance.on('an_event', function () {
  console.log('an event has happened');
});

// trigger the event
masterInstance.emit('an_event');

Update: as many users pointed out, the 'standard' way of doing that in Node would be to use 'util.inherits':

var EventEmitter = require('events').EventEmitter;
util.inherits(Master, EventEmitter);
require('events').EventEmitter

BTW, the convention for instances is to lowercase the first letter, so MasterInstance should be masterInstance.

util.inherits does a nasty thing of injecting the super_ property into the Master object. It's unnecessary and tries to treat prototypical inheritance like classic inheritance. Take a look at the bottom of this page for explanation.

@loretoparisi just Master.prototype = EventEmitter.prototype;. No need for supers. You can also use ES6 extends (and it's encouraged in Node.js docs on util.inherits) like this class Master extends EventEmitter - you get classical super(), but without injecting anything into Master.

Node.js - inheriting from EventEmitter - Stack Overflow

node.js eventemitter