DEV Community

Cover image for 10 Most Asked Questions On Node.js
KiranPoudel98 for Truemark Technology

Posted on • Originally published at thedevpost.com

10 Most Asked Questions On Node.js

Node.js is the server-side JavaScript runtime environment that executes JavaScript outside of the browser. So, today we have brought a list of most frequently asked questions on Node.js.

10 Most Asked Questions on Node.js

1. How to update npm on Windows?

Answer:

This is the new best way to upgrade npm on Windows.

Run PowerShell as Administrator

Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
Enter fullscreen mode Exit fullscreen mode

Note: Do not run npm i -g npm. Instead, use npm-windows-upgrade to update npm going forward. Also if you run the NodeJS installer, it will replace the node version.

Alternative Answer:

Download and run the latest MSI. The MSI will update your installed node and npm.

2. How to measure the time taken by a function to execute?

Answer:

Using performance.now():

var t0 = performance.now()

doSomething()   // <---- The function you're measuring time for 

var t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
Enter fullscreen mode Exit fullscreen mode

NodeJs: it is required to import the performance class.

Using console.time: (living standard)

console.time('someFunction')

someFunction() // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction')
Enter fullscreen mode Exit fullscreen mode

Note:
The string being pass to the time() and timeEnd() methods must match
(for the timer to finish as expected).

console.time() documentations:

Alternative Answer:

use new Date().getTime()

The getTime() method returns the number of milliseconds since midnight of January 1, 1970.

example:

var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
Enter fullscreen mode Exit fullscreen mode

3. How to update NodeJS and NPM to the next versions?

Answer:

You can see the docs for the update command:

npm update [-g] [<pkg>...]
Enter fullscreen mode Exit fullscreen mode

This command will update all the packages listed to the latest version (specified by the tag config), respecting semver.

Additionally, see the documentation on Node.js and NPM installation and Upgrading NPM.

The following answer should work for Linux and Mac:

npm install -g npm
Enter fullscreen mode Exit fullscreen mode

Please note that this command will remove your current version of npm. Make sure to use sudo npm install -g npm if on a Mac.

You can also update all outdated local packages by doing npm update without any arguments, or global packages by doing npm update -g.

Occasionally, the version of npm will progress such that the current version cannot be properly installed with the version that you have installed already. (Consider, if there is ever a bug in the update command.) In those cases, you can do this:

curl https://www.npmjs.com/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

To update Node.js itself, we recommend you use nvm, the Node Version Manager.

Alternative Answer:

We found this really neat way of updating node on David Walsh’s blog, you can do it by installing n:

sudo npm cache clean -f
sudo npm install -g n
sudo n stable
Enter fullscreen mode Exit fullscreen mode

It will install the current stable version of node.

Please don’t use n anymore. We recommend using nvm. You can simply install stable by following the commands below:

nvm ls-remote
nvm install <version> 
nvm use <version>
Enter fullscreen mode Exit fullscreen mode

4. How to upgrade Node.js to the latest version on Mac OS?

Answer:

Here’s how to successfully upgrade from v0.8.18 to v0.10.20 without any other requirements like brew etc. (type these commands in the terminal):

  • sudo npm cache clean -f (force) clear you npm cache
  • sudo npm install -g n install n (this might take a while)
  • sudo n stable upgrade to the current stable version

Note that sudo might prompt your password.

Additional note regarding step 3: stable can be exchanged for latest, lts (long term support) or any specific version number such as 0.10.20.

If the version number doesn’t show up when typing node -v, you might have to reboot.

These instructions are found here as well: davidwalsh.name/upgrade-nodejs
More info about the n package found here: npmjs.com/package/n
More info about Node.js’ release schedule: github.com/nodejs/Release

Alternative Answer:

If you initially installed Node.js with Homebrew, run:

brew update
brew upgrade node
npm install -g npm
Enter fullscreen mode Exit fullscreen mode

Or as a one-liner:

brew update && brew upgrade node && npm install -g npm
Enter fullscreen mode Exit fullscreen mode

A convenient way to change versions is to use nvm:

brew install nvm
Enter fullscreen mode Exit fullscreen mode

To install the latest version of Node.js with nvm:

nvm install node
Enter fullscreen mode Exit fullscreen mode

If you installed via a package, then download the latest version from nodejs.org. See Installing Node.js and updating npm.

5. How to completely uninstall Node.js and reinstall from the beginning (Mac OS X)?

Answer:

Apparently, there was a /Users/myusername/local folder that contained a include with node and lib with node and node_modules. Don’t know how and why this was created instead of in /usr/local folder.

Deleting these local references fixed the phantom v0.6.1-pre.

You may need to do the additional instructions as well:

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
Enter fullscreen mode Exit fullscreen mode

which is the equivalent of (same as above)…

sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp 
Enter fullscreen mode Exit fullscreen mode

or (same as above) broken down.

To completely uninstall node + npm is to do the following:

  • go to /usr/local/lib and delete any node and node_modules
  • go to /usr/local/include and delete any node and node_modules directory
  • if you installed with brew install node, then run brew uninstall node in your terminal
  • check your Home directory for any local or lib or include folders, and delete any node or node_modules from there
  • go to /usr/local/bin and delete any node executable

You may also need to do:

sudo rm -rf /opt/local/bin/node /opt/local/include/node /opt/local/lib/node_modules
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node.1 /usr/local/lib/dtrace/node.d
Enter fullscreen mode Exit fullscreen mode

Additionally, NVM modifies the PATH variable in $HOME/.bashrc, which must be reverted manually.

Then download nvm and follow the instructions to install node. The latest versions of node come with npm, we believe, but you can also reinstall that as well.

Alternative Answer:

For brew users, OSX:

To remove:

brew uninstall node; 
# or `brew uninstall --force node` which removes all versions
brew cleanup;
rm -f /usr/local/bin/npm /usr/local/lib/dtrace/node.d;
rm -rf ~/.npm;
Enter fullscreen mode Exit fullscreen mode

To install:

brew install node;
which node # => /usr/local/bin/node
export NODE_PATH='/usr/local/lib/node_modules' # <--- add this ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

You can run brew info node for more details regarding your node installs.

Consider using NVM instead of brew

NVM (Node version manager) is a portable solution for managing multiple versions of node

https://github.com/nvm-sh/nvm

> nvm uninstall v4.1.0
> nvm install v8.1.2
> nvm use v8.1.2
> nvm list
         v4.2.0
         v5.8.0
        v6.11.0
->       v8.1.2
         system
Enter fullscreen mode Exit fullscreen mode

You can use this with AVN to automatically switch versions as you hop between different projects with different node dependencies.

6. How to get GET (query string) variables in Express.js on Node.js?

Answer:

In Express it’s already done for you and you can simply use req.query for that:

var id = req.query.id; // $_GET["id"]
Enter fullscreen mode Exit fullscreen mode

Otherwise, in NodeJS, you can access req.url and the builtin url module to url.parse it manually:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Enter fullscreen mode Exit fullscreen mode

7. How to send command-line arguments to npm script?

Answer:

It’s possible to pass args to npm run as of npm 2.0.0

The syntax is as follows:

npm run <command> [-- <args>]
Enter fullscreen mode Exit fullscreen mode

Note- It is needed to separate the params passed to npm command itself and params passed to your script.

So if you have in package.json

"scripts": {
    "grunt": "grunt",
    "server": "node server.js"
}
Enter fullscreen mode Exit fullscreen mode

Then the following commands would be equivalent:

grunt task:target => npm run grunt -- task:target

node server.js --port=1337 => npm run server -- --port=1337
Enter fullscreen mode Exit fullscreen mode

To get the parameter value, see this question. For reading named parameters, it’s probably best to use a parsing library like yargs or minimist; nodejs exposes process.argv globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).

Like some kind of workaround (though not very handy), you can do as follows:

Say your package name from package.json is myPackage and you have also

"scripts": {
    "start": "node ./script.js server"
}
Enter fullscreen mode Exit fullscreen mode

Then add in package.json:

"config": {
    "myPort": "8080"
}
Enter fullscreen mode Exit fullscreen mode

And in your script.js:

// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080
Enter fullscreen mode Exit fullscreen mode

That way, by default npm start will use 8080. You can, however, configure it (the value will be stored by npm in its internal storage):

npm config set myPackage:myPort 9090
Enter fullscreen mode Exit fullscreen mode

Then, when invoking npm start, 9090 will be used (the default from package.json gets overridden).

Alternative Answer:

If you want to run something like npm start 8080. This is possible without needing to modify script.js or configuration files as follows.

For example, in your "scripts" JSON value, include–

"start": "node ./script.js server $PORT"
Enter fullscreen mode Exit fullscreen mode

And then from the command-line:

$ PORT=8080 npm start
Enter fullscreen mode Exit fullscreen mode

It is confirmed that this works using bash and npm 1.4.23. Note that this workaround does not require GitHub npm issue #3494 to be resolved.

8. How to install packages using node package manager in Ubuntu?

Answer:

sudo apt-get install nodejs-legacy
Enter fullscreen mode Exit fullscreen mode

First of all, lets clarify the situation a bit. In summer 2012 Debian maintainers decided to rename Node.js executable to prevent some kind of namespace collision with another package. It was very hard decision for Debian Technical Committee, because it breaks backward compatibility.

The following is a quote from Committee resolution draft, published in Debian mailing list:

  • The nodejs package shall be changed to provide /usr/bin/nodejs, not /usr/bin/node. The package should declare a Breaks: relationship with any packages in Debian that reference /usr/bin/node.
  • The nodejs source package shall also provide a nodejs-legacy binary package at Priority: extra that contains /usr/bin/node as a symlink to /usr/bin/nodejs. No package in the archive may depend on or recommend the nodejs-legacy package, which is provided solely for upstream compatibility. This package declares shall also declare a Conflicts: relationship with the node package.

Paragraph 2 is the actual solution for OP’s issue. OP should try to install this package instead of doing symlink by hand. Here is a link to this package in Debian package index website.

It can be installed using sudo apt-get install nodejs-legacy.

We have not found any information about adopting the whole thing by NPM developers, but we think npm package will be fixed on some point and nodejs-legacy become really legacy.

Alternative Answer:

Try linking node to nodejs. First, find out where nodejs is

whereis nodejs
Enter fullscreen mode Exit fullscreen mode

Then soft link node to nodejs

ln -s [the path of nodejs] /usr/bin/node 
Enter fullscreen mode Exit fullscreen mode

/usr/bin might be in your execution path. Then you can test by typing node or npm into your command line, and everything should work now.

9. How to check Node.js version on the command line? (not the REPL)

Answer:

The command line for that is:

node -v
Enter fullscreen mode Exit fullscreen mode

Or

node --version
Enter fullscreen mode Exit fullscreen mode

Note:

If node -v doesn’t work, but nodejs -v does, then something’s not set up quite right on your system. See this other question for ways to fix it.

Alternative Answer:

If you’re referring to the shell command line, either of the following will work:

node -v

node --version
Enter fullscreen mode Exit fullscreen mode

Just typing node version will cause node.js to attempt loading a module named version, which doesn’t exist unless you like working with confusing module names.

10. How to use node.js as a simple webserver?

Answer:

Simplest Node.js server is just:

$ npm install http-server -g
Enter fullscreen mode Exit fullscreen mode

Now you can run a server via the following commands:

$ cd MyApp

$ http-server
Enter fullscreen mode Exit fullscreen mode

If you’re using NPM 5.2.0 or newer, you can use http-server without installing it with npx. This isn’t recommended for use in production but is a great way to quickly get a server running on localhost.

$ npx http-server
Enter fullscreen mode Exit fullscreen mode

Or, you can try this, which opens your web browser and enables CORS requests:

$ http-server -o --cors
Enter fullscreen mode Exit fullscreen mode

For more options, check out the documentation for http-server on GitHub, or run:

$ http-server --help
Enter fullscreen mode Exit fullscreen mode

Lots of other nice features and brain-dead-simple deployment to NodeJitsu.

Feature Forks

Of course, you can easily top up the features with your own fork. You might find it’s already been done in one of the existing 800+ forks of this project:

Light Server: An Auto Refreshing Alternative

A nice alternative to http-server is light-server. It supports file watching and auto-refreshing and many other features.

npm install -g light-server 
$ light-server
Enter fullscreen mode Exit fullscreen mode

Add to your directory context menu in Windows Explorer

reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""
Enter fullscreen mode Exit fullscreen mode

Simple JSON REST server

If you need to create a simple REST server for a prototype project then json-server might be what you’re looking for.

Auto Refreshing Editors

Most web page editors and IDE tools now include a web server that will watch your source files and auto-refresh your web page when they change.

You can use Live Server with Visual Studio Code.

The open source text editor Brackets also includes a NodeJS static web server. Just open any HTML file in Brackets, press “Live Preview” and it starts a static server and opens your browser at the page. The browser will auto-refresh whenever you edit and save the HTML file. This especially useful when testing adaptive web sites. Open your HTML page on multiple browsers/window sizes/devices. Save your HTML page and instantly see if your adaptive stuff is working as they all auto-refresh.

PhoneGap Developers

If you’re coding a hybrid mobile app, you may be interested to know that the PhoneGap team took this auto-refresh concept on board with their new PhoneGap App. This is a generic mobile app that can load the HTML5 files from a server during development. This is a very slick trick since now you can skip the slow compile/deploy steps in your development cycle for hybrid mobile apps if you’re changing JS/CSS/HTML files — which is what you’re doing most of the time. They also provide the static NodeJS webserver (run phonegap serve) that detects file changes.

PhoneGap + Sencha Touch Developers

We have now extensively adapted the PhoneGap static server & PhoneGap Developer App for Sencha Touch & jQuery Mobile developers. Check it out at Sencha Touch Live. Supports –qr QR Codes and –localtunnel that proxies your static server from your desktop computer to a URL outside your firewall! Tons of uses. Massive speedup for hybrid mobile devs.

Cordova + Ionic Framework Developers

Local server and auto refresh features are baked into the ionic tool. Just run ionic serve from your app folder. Even better …ionic serve --lab to view auto-refreshing side by side views of both iOS and Android.

Alternative Answer:

You can use Connect and ServeStatic with Node.js for this:

  • Install connect and serve-static with NPM $ npm install connect serve-static
  • Create server.js file with this content: var connect = require('connect'); var serveStatic = require('serve-static'); connect() .use(serveStatic(__dirname)) .listen(8080, () => console.log('Server running on 8080...'));
  • Run with Node.js $ node server.js

You can now go to http://localhost:8080/yourfile.html

In Conclusion

These are the 10 most commonly asked questions on Node.js. If you have any suggestions regarding the article, please feel free to comment below. If you need any help, then we would be glad to help you.

We, at Truemark, provide services like web and mobile app development, digital marketing, and website development. So, if you want to work with us, please feel free to contact us.

Hope this article helped you.

This post was originally posted on DevPostbyTruemark.

Top comments (0)