Skip to content
Search

Node.js

lastmod 2026-08-19created 2014-01-08309 edits

Node.js is an event-driven I/O framework that runs on V8 (JavaScript engine). It was designed for building scalable network programs such as web servers.

Node.js is similar in purpose to Twisted, built with Python, Perl Object Environment, built with Perl, and EventMachine, built with Ruby. Unlike most JavaScript, which runs in web browsers, Node.js runs on the server side. Node.js implements some of the CommonJS specifications and includes a REPL environment for interactive testing.

Categories

How to install

Ubuntu

Alternatively, for Node.js v4:

curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs

Alternatively, for Node.js v6:

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

Optional: install build tools

## To compile and install native addons from npm you may also need to install build tools:
sudo apt-get install -y build-essential

CentOS EPEL

sudo yum install epel-release
sudo yum install nodejs
sudo yum install npm

Arch Linux

sudo pacman -S nodejs npm

Bootstrap script

#!/usr/bin/env bash

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)

N_PREFIX="$ROOT_DIR/.node"
N_DIR="$ROOT_DIR/.n"
N_EXE="$N_DIR/n"
NODE_EXE="$N_PREFIX/bin/node"
NODE_VERSION=18.12.0

if [[ ! -d "$N_DIR" ]]; then
    mkdir -vp "$N_DIR"
fi
if [[ ! -x "$N_EXE" ]]; then
    curl -L "https://raw.githubusercontent.com/tj/n/master/bin/n" -o "$N_EXE"
    chmod +x "$N_EXE"
fi
if [[ ! -x "$N_EXE" ]]; then
    echo "Could not find executable n command on path '$N_EXE'"
    exit 1
fi

if [[ ! -x "$NODE_EXE" ]]; then
    echo "Could not find executable node command on path '$NODE_EXE'"
    echo "Install node $NODE_VERSION ..."

    N_PREFIX="$N_PREFIX" "$N_EXE" install "$NODE_VERSION"

    CODE=$?
    if [[ $CODE -ne 0 ]]; then
        echo "Node $NODE_VERSION installation failed: $CODE"
        exit $CODE
    fi

    echo "Install yarn ..."
    N_PREFIX="$N_PREFIX" "$N_EXE" exec "$NODE_VERSION" npm install --global "yarn"
fi

# Read `.env` variables
if [[ -f "$ROOT_DIR/.env" ]]; then
    while read line; do
        if [[ $(echo "$line" | grep -E '^[ \t]*export[ \t]*[_a-zA-Z0-9]+=.*$') ]]; then
            eval "$line"
        else
            eval "export $line"
        fi
    done < "$ROOT_DIR/.env"
fi

export PATH="$N_PREFIX/bin:$PATH"
N_PREFIX="$N_PREFIX" "$N_EXE" exec "$NODE_VERSION" yarn "$@"

Example

A hello world HTTP server written in Node.js:

var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8000);

console.log('Server running at http://localhost:8000/');

Another example, a simple TCP Echo server that opens port 7000:

var net = require('net');

net.createServer(function (stream) {
    stream.write('hello\r\n');

    stream.on('end', function () {
        stream.end('goodbye\r\n');
    });

    stream.pipe(stream);
}).listen(7000);

GET / POST Parameter In Node.js

var sys = require ('sys'),
url = require('url'),
http = require('http'),
qs = require('querystring');

http.createServer(function (req, res) {
    if(req.method=='POST') {
        var body='';
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var POST =  qs.parse(body);
            console.log(POST);
        });
    } else if(req.method=='GET') {
        var url_parts = url.parse(req.url,true);
        console.log(url_parts.query);
    }
}).listen(1337, "127.0.0.1");

How to send a system command:

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

Obtain envronment variables

process.env.ENV_VARIABLE

Executable path

How to check the executable path:

  • process.execPath should be what you require.
  • process.argv0 is not alway pointed to node binary.

Testing HTTP connections from the command line

Readable code:

const http = require('http');

http.get('http://localhost:8080', res => {
  if (res.statusCode === 200) {
    process.exit(0);
  } else {
    console.error(`status error: ${res.statusCode}`);
    process.exit(1);
  }
});

One-liner for bash scripts:

node -e 'require("http").get("http://localhost:8080", res => res.statusCode === 200 ? process.exit(0) : process.exit(1));'

Filesystem

__filename
Get the current file path
__dirname
How to get the current directory path

File Logging

Using __defineGetter__

According to MDN, __defineGetter__ is non-standard and a deprecated API, but it can currently be used in Node.js (i.e., V8 still supports it). This oddly named __defineGetter__ binds an object's property to a function so that the bound function is called when the property is looked up. If you search for ways to intercept stdout and stderr, this method comes up a lot.

fs = require('fs');

console.log('first log message');
console.error('first error message');

var oldStdout = process.stdout,
    oldStderr = process.stderr,
    newStdout = fs.createWriteStream('log.log', {flags: 'a'}),
    newStderr = fs.createWriteStream('err.log', {flags: 'a'});

// stdout, stderr 가로챔
process.__defineGetter__('stdout', function() {
  return newStdout;
});

process.__defineGetter__('stderr', function() {
  return newStderr;
});

console.log('second log message');
console.error('second error message');

// stdout, stderr 복구
process.__defineGetter__('stdout', function() {
  return oldStdout;
});

process.__defineGetter__('stderr', function() {
  return oldStderr;
});

console.log('third log message');
console.error('third error message');

Overriding the write function

The __defineGetter__ approach works fine too, but using the non-standard __defineGetter__ feels a little uncomfortable. stdout and stderr have a write function that does the actual message output, and since this is the function that really prints the messages, you can intercept the whole function.

var fs = require('fs');

console.log('first log message');
console.error('first error message');

var oldStdoutWrite = process.stdout.write,
    oldStderrWrite = process.stderr.write;

// stdout, stderr 가로챔
process.stdout.write = function(str, encoding, fg) {
  fs.appendFile('log.log', str, function(err) {});
}
process.stderr.write = function(str, encoding, fg) {
  fs.appendFile('err.log', str, function(err) {});
}

console.log('second log message');
console.error('second error message');

// stdout, stderr 복구
process.stdout.write = oldStdoutWrite;
process.stderr.write = oldStderrWrite;

console.log('third log message');
console.error('third error message');

TDD

Server And Client App Test

When testing with Node.js, you’ll typically use the following:

Debugging

Corepack

The Node.js Technical Steering Committee (TSC) decided by official vote to stop distributing Corepack bundled with Node.js. This applies from Node.js 25; in Node.js 24 and below, it remains available as an experimental feature.

Corepack's role and limitations

  • Corepack is an experimental tool introduced in Node.js 16.9.0 that lets you use package managers such as Yarn and pnpm without installing them separately
  • Helps projects enforce a specific package manager version
  • However, it was not widely used due to low user awareness and misunderstanding of its purpose
  • Skepticism exists about bundling package managers, which should operate independently of the runtime, into Node.js

Cons

ENOSPC: System limit for number of file watchers reached

[Browsersync] Proxying: http://localhost
[Browsersync] Access URLs:
 -------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.16:3000
 -------------------------------------
          UI: http://localhost:3001
 UI External: http://localhost:3001
 -------------------------------------
[Browsersync] Watching files...
node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error: ENOSPC: System limit for number of file watchers reached, watch '/my-project-folder/vendor/myclabs/deep-copy/.github'
    at FSWatcher.<computed> (node:internal/fs/watchers:244:19)
    at Object.watch (node:fs:2247:34)
    at createFsWatchInstance (/my-project-folder/node_modules/chokidar/lib/nodefs-handler.js:119:15)
    at setFsWatchListener (/my-project-folder/node_modules/chokidar/lib/nodefs-handler.js:166:15)
    at NodeFsHandler._watchWithNodeFs (/my-project-folder/node_modules/chokidar/lib/nodefs-handler.js:331:14)
    at NodeFsHandler._handleDir (/my-project-folder/node_modules/chokidar/lib/nodefs-handler.js:559:19)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async NodeFsHandler._addToNodeFs (/my-project-folder/node_modules/chokidar/lib/nodefs-handler.js:609:16)
Emitted 'error' event on FSWatcher instance at:
    at FSWatcher._handleError (/my-project-folder/node_modules/chokidar/index.js:647:10)
    at NodeFsHandler._addToNodeFs (/my-project-folder/node_modules/chokidar/lib/nodefs-handler.js:637:18)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  errno: -28,
  syscall: 'watch',
  code: 'ENOSPC',
  path: '/my-project-folder/vendor/myclabs/deep-copy/.github',
  filename: '/my-project-folder/vendor/myclabs/deep-copy/.github'
}

... you may see it spit out an error similar to this.

The cause is said to be that the system's file watchers have reached their limit.

# 현재 한도 확인 / check current limits
cat /proc/sys/fs/inotify/max_user_watches
cat /proc/sys/fs/inotify/max_user_instances

# 영구 설정 / persist settings
sudo tee /etc/sysctl.d/99-inotify.conf > /dev/null <<'EOF'
fs.inotify.max_user_watches=524288
fs.inotify.max_user_instances=1024
EOF

sudo sysctl --system

Raising max_user_instances as well is recommended. Quite often there are enough watchers, but the instance limit is hit and the same ENOSPC appears.

Memory cost

Each watcher takes about 1KB (~1080 bytes on 64-bit). 524288 watchers come to at most about 540MB, but only the watchers actually registered use memory, so on a 128GB machine it is not worth worrying about.

Simple solution

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Note that increasing max_user_watches is not a cure-all. You can also reduce the number of watched files.

Limiting watch targets

Remove directories like node_modules from the watch targets.

mix.browserSync({
   proxy: 'ws-dev.localhost',
   files: [
      'wp-content/themes/ws/**/*.php',
      'wp-content/themes/ws/build/*.js',
      'wp-content/themes/ws/js/*.js',
      'wp-content/themes/ws/build/*.css',
   ]
});

Checking memory usage and processors

find /proc/*/fd -lname anon_inode:inotify | cut -d/ -f3 | xargs -I '{}' -- ps --no-headers -o '%p %U %c' -p '{}' | uniq -c | sort -nr

Troubleshooting

ENOSPC: System limit for number of file watchers reached

See #ENOSPC: System limit for number of file watchers reached.

caniuse-lite is outdated

Warning message output:

rowserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

Just run it as it says:

npx browserslist@latest --update-db

Initialization error (ESLint). Object.hasOwn is not a function

Initialization error (ESLint). Object.hasOwn is not a function
TypeError: Object.hasOwn is not a function
    at /home/zer0/Project/app.cvp.run/node_modules/espree/dist/espree.cjs:917:20
    at Object.<anonymous> (/home/zer0/Project/app.cvp.run/node_modules/espree/dist/espree.cjs:927:2)
    at Module._compile (internal/modules/cjs/loader.js:1114:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
    at Module.load (internal/modules/cjs/loader.js:979:32)
    at Function.Module._load (internal/modules/cjs/loader.js:819:12)
    at Module.require (internal/modules/cjs/loader.js:1003:19)
    at require (internal/modules/cjs/helpers.js:107:18)
    at Object.<anonymous> (/home/zer0/Project/app.cvp.run/node_modules/eslint/lib/languages/js/index.js:15:16)
    at Module._compile (internal/modules/cjs/loader.js:1114:14)
Process finished with exit code -1

A problem caused by an old node version. Object.hasOwn is a method added in Node.js 16.9.0, and the problem occurs because the Node.js version currently in use is older than that.

node::OOMErrorHandler

❯ 2026-08-19T03:17:12.848Z    Initializing build environment...
  2026-08-19T03:17:14.887Z    Success: Finished initializing build environment
  2026-08-19T03:17:15.767Z    Cloning repository...
  2026-08-19T03:17:21.043Z    Detected the following tools from environment: [email protected], [email protected]
  2026-08-19T03:17:21.046Z    Restoring from dependencies cache
  2026-08-19T03:17:21.048Z    Restoring from build output cache
  2026-08-19T03:17:21.204Z    Installing project dependencies: npm clean-install --progress=false
  2026-08-19T03:17:42.105Z    npm warn deprecated [email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
  2026-08-19T03:17:43.565Z    npm warn deprecated [email protected]: Use @arcgis/core instead.
  2026-08-19T03:17:44.098Z    npm warn deprecated [email protected]: Active development of CryptoJS has been discontinued. This library is no longer maintained.
  2026-08-19T03:18:20.873Z    npm warn deprecated [email protected]: 1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide
  2026-08-19T03:18:56.618Z
  2026-08-19T03:18:56.618Z    added 1628 packages, and audited 1630 packages in 2m
  2026-08-19T03:18:56.621Z
  2026-08-19T03:18:56.621Z    281 packages are looking for funding
  2026-08-19T03:18:56.622Z      run `npm fund` for details
  2026-08-19T03:18:56.727Z
  2026-08-19T03:18:56.731Z    15 high severity vulnerabilities
  2026-08-19T03:18:56.731Z
  2026-08-19T03:18:56.732Z    To address issues that do not require attention, run:
  2026-08-19T03:18:56.732Z      npm audit fix
  2026-08-19T03:18:56.732Z
  2026-08-19T03:18:56.732Z    To address all issues (including breaking changes), run:
  2026-08-19T03:18:56.732Z      npm audit fix --force
  2026-08-19T03:18:56.732Z
  2026-08-19T03:18:56.732Z    Run `npm audit` for details.
  2026-08-19T03:18:56.733Z    npm warn allow-scripts 9 packages have install scripts not yet covered by allowScripts:
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   [email protected] (postinstall: node install.js)
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   [email protected] (postinstall: node install.js)
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   [email protected] (postinstall: node install.js)
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   @vaadin/[email protected] (postinstall: node check.cjs)
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   [email protected] (postinstall: node install.js)
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   [email protected] (postinstall: node ./updateFontList.js)
  2026-08-19T03:18:56.733Z    npm warn allow-scripts   [email protected] (install: node install/check.js || npm run build)
  2026-08-19T03:18:56.734Z    npm warn allow-scripts   [email protected] (postinstall: node install.js)
  2026-08-19T03:18:56.734Z    npm warn allow-scripts   [email protected] (postinstall: node install.js)
  2026-08-19T03:18:56.734Z    npm warn allow-scripts
  2026-08-19T03:18:56.734Z    npm warn allow-scripts Run `npm approve-scripts --allow-scripts-pending` to review, or `npm approve-scripts <pkg>` to allow.
  2026-08-19T03:18:57.200Z    Executing user build command: npm run build
  2026-08-19T03:18:57.682Z
  2026-08-19T03:18:57.682Z    > build
  2026-08-19T03:18:57.682Z    > tsc -b && cross-env NODE_OPTIONS=--max-old-space-size=6144 vite build
  2026-08-19T03:18:57.683Z
  2026-08-19T03:21:32.456Z
  2026-08-19T03:21:32.457Z    <--- Last few GCs --->
  2026-08-19T03:21:32.460Z
  2026-08-19T03:21:32.472Z    [888:0x2a206000]   152096 ms: Scavenge 2036.1 (2050.8) -> 2029.7 (2050.8) MB, pooled: 0 MB, 7.74 / 0.00 ms  (average mu = 0.266, current mu = 0.197) allocation failure;
  2026-08-19T03:21:32.472Z    [888:0x2a206000]   154699 ms: Mark-Compact (reduce) 2041.9 (2056.3) -> 2034.1 (2040.8) MB, pooled: 0 MB, 794.80 / 0.00 ms  (+ 1633.4 ms in 188 steps since start of marking, biggest step 20.0 ms, walltime since start of marking 2603 ms) (average mu = 0.257
  2026-08-19T03:21:32.473Z    FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
  2026-08-19T03:21:32.473Z    ----- Native stack trace -----
  2026-08-19T03:21:32.473Z
  2026-08-19T03:21:32.473Z     1: 0x74eae8 node::OOMErrorHandler(char const*, v8::OOMDetails const&) [node]
  2026-08-19T03:21:32.473Z     2: 0xc42680  [node]
  2026-08-19T03:21:32.473Z     3: 0xc4276f  [node]
  2026-08-19T03:21:32.473Z     4: 0xee5fc5  [node]
  2026-08-19T03:21:32.487Z     5: 0xee5ff2  [node]
  2026-08-19T03:21:32.487Z     6: 0xee62ea  [node]
  2026-08-19T03:21:32.487Z     7: 0xef6fea  [node]
  2026-08-19T03:21:32.487Z     8: 0xefb390  [node]
  2026-08-19T03:21:32.487Z     9: 0x198d931  [node]
  2026-08-19T03:21:35.443Z    Aborted (core dumped)
  2026-08-19T03:21:35.511Z    Failed: error occurred while running build command

This error occurs when building in an environment without enough memory. Adjust node's memory option in the .npmrc file.

# tsc and vite both need more heap than Node's default (~2GB on the 8GB
# Cloudflare build container) to get through this codebase. npm exports this
# as NODE_OPTIONS for every lifecycle script, so no single command can be
# missed the way a per-command flag can.
node-options=--max-old-space-size=6144

See also

  • Event driven architecture
  • left-pad (NPM, the left-pad incident)
  • deno
  • Bun - Fast JavaScript runtime/transpiler/NPM client based on JavaScriptCore
  • Bare - Fast, lightweight, modular JavaScript runtime
  • php-node - Handler that processes PHP HTTP requests within Node.js
  • qnm - CLI tool for looking into the node_modules folder
  • edgejs - Secure WebAssembly-based JS runtime

Favorite site

Article

Tutorial

Guide

Packages

Deploy

Stack

References


  1. Seokjun.kim_-_node-js-tdd.pdf ↩

  2. The_Node_Beginner_Book_(Korean_version)_A_comprehensive_Node.pdf ↩

  3. Felix's_node.js_Beginners_Guide.pdf ↩

  4. Node_v0.2.6-ko.pdf ↩

  5. Bcho.tistory.com_-node.js-_Introduction_and_internal_structure.pdf ↩

  6. Node.js_File_System.pdf ↩

  7. Dockerizing_a_NodeJS_web_app_-_Node.pdf ↩

  8. Naver_D2_-Nodejs-_Quickly_develop_services.pdf ↩

author Zer0 sitemap