• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / NodeJS Tips And Tricks For Beginners

NodeJS Tips And Tricks For Beginners

April 26, 2015 by Rana Ahsan 2 Comments

nodejs tips tricks

Over time, I learned a few useful facts while working with NodeJS that made my life a lot easier at the beginning stage. I tried to compile them into a list on this post. As a NodeJS developer, you may find at least some of these NodeJS tips helpful as well.

Using Strict Mode In Coding:

using strict mode in Nodejs code helps us to figure out poorly written JavaScript syntax and forces us to write better code syntax. To use this, just add the following line in every JavaScript file you create/write code on:

'use strict'; //rest of your NodeJS code goes here.
Code language: JavaScript (javascript)

For example, in a javascript file without strict mode, you can initialize a new variable even without the ‘var’ keyword.

abcd = "some string value";
Code language: JavaScript (javascript)

It won’t result in any errors. But in the case of using ‘use strict’, it will throw an error like the below:

iterate = "some string value" ^ ReferenceError: abcd is not defined
Code language: JavaScript (javascript)

Thus forcing you to write a little bit more structured code. Which is very useful in generating quality code with such a dynamic language as JavaScript.

Use Node shell:

If you are trying to test a NodeJS function on how it works, the NodeJS shell works a lot better for that. Just run ‘node,’ and it will bring you up the node shell. write code just like in a text editor, and it will work fine. However, when you are done exiting the node shell, it doesn’t have support for ‘exit’/’quit’ or similar commands, just like other CLI tools. You must write a valid NodeJS statement that tells you to exit the process. Here is the command you will need for that.

$process.exit(0)
Code language: PHP (php)


On my first day of NodeJS/shell using, I had no idea how to exit the shell and had to google to figure out this way.

Using global variable As Cache:

If you are creating a comparatively small app where it will be an overhead to integrate a third-party caching mechanism, you can handle those right inside your NodeJS app, given that you are running it in a default single-threaded mode.

As being single-threaded, only one instance of Nodejs application is running(just like a desktop app) to process all requests, unlike other web programming languages PHP/ruby/python etc based apps. Declaring a global variable there persists and is accessible to all requests. So, you should always be careful about that too.

To achieve such a mechanism, create a global variable of necessary types(JSON/array) and inside your function, add necessary manipulation mechanism for that variable. it will persist across all requests.

'use strict'; //this is your cache for this js file var cache = {}; exports.someMethod = function(data){ /*Your business logic*/ //set cache cache[key] = val; //retrieve cache cachedVal = cache[key]; //delete cache delete cache[key]; /*Your business logic*/ }
Code language: JavaScript (javascript)

Easy Logging Without any third-party library:

We usually use the ‘console.log’ method for printing temporary info while development and some good logging libraries for logging
in the deployment stage. If you are lazy enough and trying to avoid third-party logging libraries, there’s good news for you. You can still get a decent logging system on your NodeJS app with native support.

The ‘console’ object in NodeJS has several different levels for logging(error/info/warn etc), which you can check more here on the console object’s official documentation page. Use them appropriately as needed. Then, while running the NodeJS app, refer to a log file where you want everything written as below:

$node app.js > mylog.log
Code language: PHP (php)

And you are set. All information will be logged in the log file, which can be checked later for useful information.

One more thing about the console object, we usually use the following format to print something to the terminal window:

console.log("I am trying to see the value of abc"+abc);
Code language: JavaScript (javascript)

It works for the single-valued item. For JSON/objects, we can use ‘console.log(abc)’ , but it won’t work with ‘+’ operator. Here we can use ‘,’ separator to print different values:

console.log("I am trying to see the value of abc", abc);
Code language: JavaScript (javascript)

This may look obvious to some of you. But interestingly, I didn’t know or even try this for my first few days of NodeJS. So, other beginners might find this useful.

Avoid using “*” in production dependency:

In your package.json file, you can specify a version to use or keep ‘*’ to have the latest version always. It’s a good way to have all of your packages updated to their latest version, which might have several improvements, bug fixes, and new features included. But this makes sense as long as you are working only in development mode and the product isn’t in production yet. You can fix it if any compatibility occurs.

//instead of this: "dependencies": { "clustered-node": "*" } //use this "dependencies": { "clustered-node": "~0.0.10" }
Code language: JavaScript (javascript)


However, in a production environment, it’s very, very risky to have such a notation for dependencies. You never know which package gonna break when, and it could cause crashing your app too! So, use it in the earlier stage of development, but switch to a specific version-based dependency as soon as the product becomes in a major deployment stage.

Asynchronous looping:

We get useful support for asynchronous control flow/looping with underscoreJS/AsyncJS. However, it’s not that hard to have it natively as long as you understand the callback concepts well. So, in case you don’t want to use such libraries for a simple task, you can use the following mechanism:

var iterate = function(items, i){ console.log("handling: "+i); //async methods etc someAsyncMethod(params, function callback(){ if(items.length <= i)return; return iterate(items, ++i); }) }; var items = [1,2,3,4]; iterate(items, 0);
Code language: JavaScript (javascript)

Final Words:

This is not a completed post. Rather, it supposes to be an ongoing list of small tips for beginners. If you have something to add, write it in the comments! Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: javascript, nodejs, tips

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. heyuou@hey.com says

    July 14, 2016 at 7:28 am

    This is a nice work, (Y)

    Reply
  2. nobody says

    November 7, 2017 at 11:20 am

    exit node shell: CTRL+C, twice

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023