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


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 to start debugging.

memory leaks on nodejs 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 {
  } catch (e) {
    console.log("You must run program with 'node --expose-gc index.js' or 'npm start'");
  //2. Output Heap stats
  var heapUsed = process.memoryUsage().heapUsed;
  console.log("Program is using " + heapUsed + " bytes of Heap.")
  //3. Get Heap dump
  process.kill(, 'SIGUSR2');
setInterval(generateHeapDumpAndStats, 2000); //Do garbage collection and heap dump every 2 seconds

Categories: , ,


Leave a Comment