NodeJS cheasheet

1 minute read

Setup a new project

npm init # => first step to create an empty project. (we choose app.js instead of index.js when asked).
npm install # => then you have to install dependencies.
node app.js
npm install express --save
npm install body-parser --save # => will allow you to parse with express etc.
npm install -g nodemon # => so you don't need to restart your nodejs
npm install ejs --save # => html templating.

Remote debug nodejs app / use chrome developers to detect memory leaks

Step 1 enable remote debug on a running nodejs process

kill -SIGUSR1 $NODEJS_PID

Now your nodejs process (V8) is listening on port 5858

Step 2 run node-inspector

# node-inspector --web-port=8081 --save-live-edit
Node Inspector v0.12.8
Visit http://127.0.0.1:8081/?port=5858 to start debugging.

memory leaks on nodejs

Alexkras.com on nodejs memory leaks does an excellent work on describing how to work on memory leaks on nodejs.

A brief summary from it:

  1. Reproduce the problem - plot memory heap after triggering gc like every 2 seconds, see that memory increases:
function generateHeapDumpAndStats(){
  //1. Force garbage collection every time this function is called
  try {
    global.gc();
  } catch (e) {
    console.log("You must run program with 'node --expose-gc index.js' or 'npm start'");
    process.exit();
  }
 
  //2. Output Heap stats
  var heapUsed = process.memoryUsage().heapUsed;
  console.log("Program is using " + heapUsed + " bytes of Heap.")
 
  //3. Get Heap dump
  process.kill(process.pid, 'SIGUSR2');
}
setInterval(generateHeapDumpAndStats, 2000); //Do garbage collection and heap dump every 2 seconds

Categories: , ,

Updated:

Leave a Comment