node-dev 6: Zero-Conf Node Process Restarting

node-dev 6: Zero-Conf Node Process Restarting

Node-dev is a development tool for Node.js that automatically restarts the node process when a file is modified. Node-dev uses filewatcher under the hood and hence will take advantage of the native fs.watch() API if it is available on your system.

node-dev

Node-dev is a development tool for Node.js that automatically restarts the node process when a file is modified.

In contrast to tools like supervisor or nodemon it doesn't scan the filesystem for files to be watched. Instead it hooks into Node's require() function to watch only the files that have been actually required.

This means that you don't have to configure any include- or exclude rules. If you modify a JS file that is solely used on the client-side but never run on the server, node-dev will know this and won't restart the process.

This also means that you don't have to configure any file extensions. Just require a .json file or a .coffee script for example and it will be watched. Automatically.

Node-dev uses filewatcher under the hood and hence will take advantage of the native fs.watch() API if it is available on your system.

Usage

Just run node-dev as you would normally run node:

node-dev foo.js

There are a couple of command line options that can be used to control which files are watched and what happens when they change:

  • --clear - Clear the screen on restart
  • --dedupe - Dedupe dynamically
  • --deps:
  • -1 - Watch the whole dependency tree
  • 0 - Watch only the project's own files and linked modules (via npm link)
  • 1 (Default) - Watch all first level dependencies
  • --fork - Hook into child_process.fork
  • --graceful_ipc <msg> - Send 'msg' as an IPC message instead of SIGTERM for restart/shutdown
  • --ignore - A file whose changes should not cause a restart
  • --notify - Display desktop notifications
  • --poll - Force polling for file changes (Caution! CPU-heavy!)
  • --respawn - Keep watching for changes after the script has exited
  • --timestamp - The timestamp format to use for logging restarts
  • --vm - Load files using Node's VM

By default node-dev will watch all first-level dependencies, i.e. the ones in the project's node_modulesfolder.

Installation

node-dev can be installed via npm. Installing it with the -g option will allow you to use it anywhere you would use node.

npm install -g node-dev

Desktop Notifications

Status and error messages can be displayed as desktop notification using node-notifier:

Screenshot

Screenshot

Requirements:

  • Mac OS X: >= 10.8 or Growl if earlier.
  • Linux: notify-osd installed (Ubuntu should have this by default)
  • Windows: >= 8, task bar balloon if earlier or Growl if that is installed.
  • General Fallback: Growl

Settings

Usually node-dev doesn't require any configuration at all, but there are some options you can set to tweak its behaviour:

  • clear – Whether to clear the screen upon restarts. Default: false
  • dedupe – Whether modules should by dynamically deduped. Default: false
  • deps – How many levels of dependencies should be watched. Default: 1
  • fork – Whether to hook into child_process.fork (required for clustered programs). Default: true
  • graceful_ipc - Send the argument provided as an IPC message instead of SIGTERM during restart events. Default: "" (off)
  • ignore - A single file or an array of files to ignore. Default: []
  • notify – Whether to display desktop notifications. Default: true
  • poll - Force polling for file changes, this can be CPU-heavy. Default: false
  • respawn - Keep watching for changes after the script has exited. Default: false
  • timestamp – The timestamp format to use for logging restarts. Default: "HH:MM:ss"
  • vm – Whether to watch files loaded via Node's VM module. Default: true

Upon startup node-dev looks for a .node-dev.json file in the following directories:

  • user's HOME directory
  • the current working directory (as provided by process.cwd())
  • the same directory as the script to be run

Settings found later in the list will overwrite previous options.

ESModules

When using ESModule syntax and .mjs files, node-dev will automatically use a loader to know which files to watch.

Passing arguments to node

From v6 onwards, node-dev will pass all unknown command-line arguments to the node process which should provide more flexibility for developers.

Dedupe linked modules

Sometimes you need to make sure that multiple modules get exactly the same instance of a common (peer-) dependency. This can usually be achieved by running npm dedupe – however this doesn't work when you try to npm link a dependency (which is quite common during development). Therefore node-dev provides a --dedupe switch that will inject the dynamic-dedupe module into your app.

Transpilers

You can use node-dev to run transpiled languages like TypeScript. You can either use a .js file as entry point to your application that registers your transpiler as a require-extension manually, for example by calling CoffeeScript.register() or you can let node-dev do this for you.

There is a config option called extensions which maps file extensions to compiler module names. By default the map looks like this:

    {
        "coffee": "coffee-script/register",
        "ls": "LiveScript",
        "ts": "ts-node/register"
    }

This means that if you run node-dev foo.coffee node-dev will do a require("coffee-script/register") before running your script. You will need to have coffeescript or ts-node installed as a dependency of your package for these transpilers to function.

Note: If you want to use coffee-script < 1.7 you have to change the setting to {"coffee": "coffee-script"}.

Options can be passed to a transpiler by providing an object containing name and options attributes:

    {
        "js": {
            "name": "babel-core/register",
            "options": {
                "only": [
                    "lib/**",
                    "node_modules/es2015-only-module/**"
                ]
            }
        }
    }

Graceful restarts

Node-dev sends a SIGTERM signal to the child-process if a restart is required. If your app is not listening for these signals process.exit(0) will be called immediately. If a listener is registered, node-dev assumes that your app will exit on its own once it is ready.

Windows does not handle POSIX signals, as such signals such as SIGTERM cause the process manager to unconditionally terminate the application with no chance of cleanup. In this case, the option graceful_ipc may be used. If this option is defined, the argument provided to the option will be sent as an IPC message via child.send("<graceful_ipc argument>"). The child process can listen and handle this event with:

process.on("message", function (msg) {
  if (msg === "<graceful_ipc argument") {
    // Gracefully shut down here
    doGracefulShutdown();
  }
});

Ignore paths

If you’d like to ignore certain paths or files from triggering a restart simply list them in the .node-dev.json configuration under "ignore", e.g.

{
  "ignore": [
    "client/scripts",
    "shared/module.js"
  ]
}

This might be useful when you are running a universal (isomorphic) web app that shares modules across the server and client, e.g. React.js components for server-side rendering, which you don’t want to trigger a server restart when changed, since it introduces an unnecessary delay.

node javascript api web-development developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

A Simple Guide to API Development Tools

APIs can be as simple as 1 endpoint for use by 100s of users or as complex as the AWS APIs with 1000s of endpoints and 100s of thousands of users. Building them can mean spending a couple of hours using a low-code platform or months of work using a multitude of tools. Hosting them can be as simple as using one platform that does everything we need or as complex as setting up and managing ingress control, security, caching, failover, metrics, scaling.

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Security Concerns for Peripheral APIs on the Web

Google has been promoting the inclusion of peripheral connectivity using Bluetooth and USB on web browsers for several years. Yet, it's meeting heavy resistance from other browser vendors such as Apple and Mozilla. While Chrome supports Web Bluetooth since 2016 and Web USB since 2017, no other vendor has concrete plans for supporting these technologies, putting the future of these Web APIs under question.

Working with Data and APIs in JavaScript - Geolocation Web API

Welcome to Working with Data and APIs in Javascript! Before diving into communication between client and server (GET and POST requests), let's look at the Geolocation Web API with navigator.geolocation. Learn how to work with data in web applications and the basics of server-side programming with Node.