NODE(1) | General Commands Manual | NODE(1) |
node
— server-side JavaScript runtime
node | [options] [v8 options] [<program-entry-point> | -e string | -- ] [arguments ...] |
node | inspect, [<program-entry-point> | -e string | <host>:<port>] ... |
node | [--v8-options ] |
Node.js is a set of libraries for JavaScript which allows it to be used outside of the browser. It is primarily focused on creating simple, easy-to-build network clients and servers.
Execute node
without arguments to start a REPL.
-
--
--abort-on-uncaught-exception
--allow-addons
When using the Permission Model, the process will not be able to use native addons by default. Attempts to do so will throw an ERR_DLOPEN_DISABLED unless the user explicitly passes the --allow-addons flag when starting Node.js. Example:
// Attempt to require an native addon require('nodejs-addon-example');
$ node --experimental-permission --allow-fs-read=* index.js node:internal/modules/cjs/loader:1319 return process.dlopen(module, path.toNamespacedPath(filename)); ^ Error: Cannot load native addon because loading addons is disabled. at Module._extensions..node (node:internal/modules/cjs/loader:1319:18) at Module.load (node:internal/modules/cjs/loader:1091:32) at Module._load (node:internal/modules/cjs/loader:938:12) at Module.require (node:internal/modules/cjs/loader:1115:19) at require (node:internal/modules/helpers:130:18) at Object.<anonymous> (/home/index.js:1:15) at Module._compile (node:internal/modules/cjs/loader:1233:14) at Module._extensions..js (node:internal/modules/cjs/loader:1287:10) at Module.load (node:internal/modules/cjs/loader:1091:32) at Module._load (node:internal/modules/cjs/loader:938:12) { code: 'ERR_DLOPEN_DISABLED' }
--allow-child-process
When using the Permission Model, the process will not be able to spawn any child process by default. Attempts to do so will throw an ERR_ACCESS_DENIED unless the user explicitly passes the --allow-child-process flag when starting Node.js. Example:
const childProcess = require('node:child_process'); // Attempt to bypass the permission childProcess.spawn('node', ['-e', 'require("fs").writeFileSync("/new-file", "example")']);
$ node --experimental-permission --allow-fs-read=* index.js node:internal/child_process:388 const err = this._handle.spawn(options); ^ Error: Access to this API has been restricted at ChildProcess.spawn (node:internal/child_process:388:28) at Object.spawn (node:child_process:723:9) at Object.<anonymous> (/home/index.js:3:14) at Module._compile (node:internal/modules/cjs/loader:1120:14) at Module._extensions..js (node:internal/modules/cjs/loader:1174:10) at Module.load (node:internal/modules/cjs/loader:998:32) at Module._load (node:internal/modules/cjs/loader:839:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47 { code: 'ERR_ACCESS_DENIED', permission: 'ChildProcess' }
--allow-fs-read
This flag configures file system read permissions using the Permission Model. The valid arguments for the --allow-fs-read flag are:
$ node --experimental-permission t.js node:internal/modules/cjs/loader:162 const result = internalModuleStat(receiver, filename); ^ Error: Access to this API has been restricted at stat (node:internal/modules/cjs/loader:162:18) at Module._findPath (node:internal/modules/cjs/loader:640:16) at resolveMainPath (node:internal/modules/run_main:15:25) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:53:24) at node:internal/main/run_main_module:23:47 { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemRead', resource: '/Users/rafaelgss/repos/os/node/t.js' }
node --experimental-permission --allow-fs-read=/path/to/index.js index.js
--allow-fs-write
This flag configures file system write permissions using the Permission Model. The valid arguments for the --allow-fs-write flag are:
--allow-wasi
When using the Permission Model, the process will not be capable of creating any WASI instances by default. For security reasons, the call will throw an ERR_ACCESS_DENIED unless the user explicitly passes the flag --allow-wasi in the main Node.js process. Example:
const { WASI } = require('node:wasi'); // Attempt to bypass the permission new WASI({ version: 'preview1', // Attempt to mount the whole filesystem preopens: { '/': '/', }, });
$ node --experimental-permission --allow-fs-read=* index.js node:wasi:99 const wrap = new _WASI(args, env, preopens, stdio); ^ Error: Access to this API has been restricted at new WASI (node:wasi:99:18) at Object.<anonymous> (/home/index.js:3:1) at Module._compile (node:internal/modules/cjs/loader:1476:14) at Module._extensions..js (node:internal/modules/cjs/loader:1555:10) at Module.load (node:internal/modules/cjs/loader:1288:32) at Module._load (node:internal/modules/cjs/loader:1104:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:191:14) at node:internal/main/run_main_module:30:49 { code: 'ERR_ACCESS_DENIED', permission: 'WASI', }
--allow-worker
When using the Permission Model, the process will not be able to create any worker threads by default. For security reasons, the call will throw an ERR_ACCESS_DENIED unless the user explicitly pass the flag --allow-worker in the main Node.js process. Example:
const { Worker } = require('node:worker_threads'); // Attempt to bypass the permission new Worker(__filename);
$ node --experimental-permission --allow-fs-read=* index.js node:internal/worker:188 this[kHandle] = new WorkerImpl(url, ^ Error: Access to this API has been restricted at new Worker (node:internal/worker:188:21) at Object.<anonymous> (/home/index.js.js:3:1) at Module._compile (node:internal/modules/cjs/loader:1120:14) at Module._extensions..js (node:internal/modules/cjs/loader:1174:10) at Module.load (node:internal/modules/cjs/loader:998:32) at Module._load (node:internal/modules/cjs/loader:839:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47 { code: 'ERR_ACCESS_DENIED', permission: 'WorkerThreads' }
--build-snapshot
Generates a snapshot blob when the process exits and writes it to disk, which can be loaded later with --snapshot-blob. When building the snapshot, if --snapshot-blob is not specified, the generated blob will be written, by default, to snapshot.blob in the current working directory. Otherwise it will be written to the path specified by --snapshot-blob.
$ echo "globalThis.foo = 'I am from the snapshot'" > snapshot.js # Run snapshot.js to initialize the application and snapshot the # state of it into snapshot.blob. $ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js $ echo "console.log(globalThis.foo)" > index.js # Load the generated snapshot and start the application from index.js. $ node --snapshot-blob snapshot.blob index.js I am from the snapshot
$ echo "require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))" > snapshot.js $ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js $ node --snapshot-blob snapshot.blob I am from the snapshot
--build-snapshot-config
Specifies the path to a JSON configuration file which configures snapshot creation behavior. The following options are currently supported:
-c
, --check
--completion-bash
node --completion-bash > node_bash_completion source node_bash_completion
-C
condition, --conditions
=conditionProvide custom conditional exports resolution conditions. Any number of custom string condition names are permitted. The default Node.js conditions of "node", "default", "import", and "require" will always apply as defined. For example, to run a module with "development" resolutions:
node -C development app.js
--cpu-prof
Starts the V8 CPU profiler on start up, and writes the CPU profile to disk before exit. If --cpu-prof-dir is not specified, the generated profile is placed in the current working directory. If --cpu-prof-name is not specified, the generated profile is named CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.
$ node --cpu-prof index.js $ ls *.cpuprofile CPU.20190409.202950.15293.0.0.cpuprofile
--cpu-prof-dir
Specify the directory where the CPU profiles generated by --cpu-prof will be placed. The default value is controlled by the --diagnostic-dir command-line option.
--cpu-prof-interval
Specify the sampling interval in microseconds for the CPU profiles generated by --cpu-prof. The default is 1000 microseconds.
--cpu-prof-name
Specify the file name of the CPU profile generated by --cpu-prof.
--diagnostic-dir
=directory--disable-warning
=code-or-typeDisable specific process warnings by code or type. Warnings emitted from process.emitWarning() may contain a code and a type. This option will not-emit warnings that have a matching code or type. List of deprecation warnings. The Node.js core warning types are: DeprecationWarning and ExperimentalWarning For example, the following script will not emit DEP0025 require('node:sys') when executed with node --disable-warning=DEP0025:
import sys from 'node:sys';
const sys = require('node:sys');
import sys from 'node:sys'; import vm from 'node:vm'; vm.measureMemory();
const sys = require('node:sys'); const vm = require('node:vm'); vm.measureMemory();
--disable-wasm-trap-handler
$ ulimit -v 5000000 $ node -p "new WebAssembly.Memory({ initial: 10, maximum: 100 });" [eval]:1 new WebAssembly.Memory({ initial: 10, maximum: 100 }); ^ RangeError: WebAssembly.Memory(): could not allocate memory at [eval]:1:1 at runScriptInThisContext (node:internal/vm:209:10) at node:internal/process/execution:118:14 at [eval]-wrapper:6:24 at runScript (node:internal/process/execution:101:62) at evalScript (node:internal/process/execution:136:3) at node:internal/main/eval_string:49:3
--disable-proto
=mode--disallow-code-generation-from-strings
--expose-gc
This flag will expose the gc extension from V8.
if (globalThis.gc) { globalThis.gc(); }
--dns-result-order
=order--enable-fips
--enable-network-family-autoselection
--enable-source-maps
const originalPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = (error, trace) => { // Modify error and trace and format stack trace with // original Error.prepareStackTrace. return originalPrepareStackTrace(error, trace); };
--entry-url
When present, Node.js will interpret the entry point as a URL, rather than a path. Follows ECMAScript module resolution rules. Any query parameter or hash in the URL will be accessible via import.meta.url.
node --entry-url 'file:///path/to/file.js?queryparams=work#and-hashes-too' node --entry-url --experimental-strip-types 'file.ts?query#hash' node --entry-url 'data:text/javascript,console.log("Hello")'
--env-file
=configLoads environment variables from a file relative to the current directory, making them available to applications on process.env. The environment variables which configure Node.js, such as NODE_OPTIONS, are parsed and applied. If the same variable is defined in the environment and in the file, the value from the environment takes precedence. You can pass multiple --env-file arguments. Subsequent files override pre-existing variables defined in previous files. An error is thrown if the file does not exist.
node --env-file=.env --env-file=.development.env index.js
PORT=3000
# This is a comment PORT=3000 # This is also a comment
USERNAME="nodejs" # will result in `nodejs` as the value.
MULTI_LINE="THIS IS A MULTILINE" # will result in `THIS IS\nA MULTILINE` as the value.
export USERNAME="nodejs" # will result in `nodejs` as the value.
--env-file-if-exists
=config-e
, --eval
script--experimental-async-context-frame
Enables the use of AsyncLocalStorage backed by AsyncContextFrame rather than the default implementation which relies on async_hooks. This new model is implemented very differently and so could have differences in how context data flows within the application. As such, it is presently recommended to be sure your application behaviour is unaffected by this change before using it in production.
--experimental-default-type
=typeDefine which module system, module or commonjs, to use for the following:
--experimental-transform-types
Enables the transformation of TypeScript-only syntax into JavaScript code. Implies --experimental-strip-types and --enable-source-maps.
--experimental-eventsource
--experimental-import-meta-resolve
--experimental-loader
=moduleSpecify the module containing exported module customization hooks. module may be any string accepted as an import specifier.
--experimental-network-inspection
Enable experimental support for the network inspection with Chrome DevTools.
--experimental-permission
Enable the Permission Model for current process. When enabled, the following permissions are restricted:
--experimental-require-module
Supports loading a synchronous ES module graph in require(). See Loading ECMAScript modules using require().
--experimental-sea-config
Use this flag to generate a blob that can be injected into the Node.js binary to produce a single executable application. See the documentation about this configuration for details.
--experimental-shadow-realm
--experimental-sqlite
--experimental-strip-types
Enable experimental type-stripping for TypeScript files. For more information, see the TypeScript type-stripping documentation.
--experimental-test-coverage
--experimental-test-isolation
=modeConfigures the type of test isolation used in the test runner. When mode is 'process', each test file is run in a separate child process. When mode is 'none', all test files run in the same process as the test runner. The default isolation mode is 'process'. This flag is ignored if the --test flag is not present. See the test runner execution model section for more information.
--experimental-test-module-mocks
Enable module mocking in the test runner.
--experimental-test-snapshots
Enable snapshot testing in the test runner.
--experimental-vm-modules
--experimental-wasi-unstable-preview1
--experimental-wasm-modules
--experimental-webstorage
--force-context-aware
--force-fips
--force-node-api-uncaught-exceptions-policy
--frozen-intrinsics
Enable experimental frozen intrinsics like Array and Object. Only the root context is supported. There is no guarantee that globalThis.Array is indeed the default intrinsic reference. Code may break under this flag. To allow polyfills to be added, --require and --import both run before freezing intrinsics.
--heap-prof
Starts the V8 heap profiler on start up, and writes the heap profile to disk before exit. If --heap-prof-dir is not specified, the generated profile is placed in the current working directory. If --heap-prof-name is not specified, the generated profile is named Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.
$ node --heap-prof index.js $ ls *.heapprofile Heap.20190409.202950.15293.0.001.heapprofile
--heap-prof-dir
Specify the directory where the heap profiles generated by --heap-prof will be placed. The default value is controlled by the --diagnostic-dir command-line option.
--heap-prof-interval
Specify the average sampling interval in bytes for the heap profiles generated by --heap-prof. The default is 512 * 1024 bytes.
--heap-prof-name
Specify the file name of the heap profile generated by --heap-prof.
--heapsnapshot-near-heap-limit
=max_countWrites a V8 heap snapshot to disk when the V8 heap usage is approaching the heap limit. count should be a non-negative integer (in which case Node.js will write no more than max_count snapshots to disk). When generating snapshots, garbage collection may be triggered and bring the heap usage down. Therefore multiple snapshots may be written to disk before the Node.js instance finally runs out of memory. These heap snapshots can be compared to determine what objects are being allocated during the time consecutive snapshots are taken. It's not guaranteed that Node.js will write exactly max_count snapshots to disk, but it will try its best to generate at least one and up to max_count snapshots before the Node.js instance runs out of memory when max_count is greater than 0. Generating V8 snapshots takes time and memory (both memory managed by the V8 heap and native memory outside the V8 heap). The bigger the heap is, the more resources it needs. Node.js will adjust the V8 heap to accommodate the additional V8 heap memory overhead, and try its best to avoid using up all the memory available to the process. When the process uses more memory than the system deems appropriate, the process may be terminated abruptly by the system, depending on the system configuration.
$ node --max-old-space-size=100 --heapsnapshot-near-heap-limit=3 index.js Wrote snapshot to Heap.20200430.100036.49580.0.001.heapsnapshot Wrote snapshot to Heap.20200430.100037.49580.0.002.heapsnapshot Wrote snapshot to Heap.20200430.100038.49580.0.003.heapsnapshot <--- Last few GCs ---> [49580:0x110000000] 4826 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed [49580:0x110000000] 4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed <--- JS stacktrace ---> FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
--heapsnapshot-signal
=signal$ node --heapsnapshot-signal=SIGUSR2 index.js & $ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND node 1 5.5 6.1 787252 247004 ? Ssl 16:43 0:02 node --heapsnapshot-signal=SIGUSR2 index.js $ kill -USR2 1 $ ls Heap.20190718.133405.15554.0.001.heapsnapshot
-h
, --help
--icu-data-dir
=file--import
=modulePreload the specified module at startup. If the flag is provided several times, each module will be executed sequentially in the order they appear, starting with the ones provided in NODE_OPTIONS. Follows ECMAScript module resolution rules. Use --require to load a CommonJS module. Modules preloaded with --require will run before modules preloaded with --import. Modules are preloaded into the main thread as well as any worker threads, forked processes, or clustered processes.
--input-type
=type--insecure-http-parser
--inspect[
=[host:]port--inspect-brk[
=[host:]port--inspect-port
=[host:]port--inspect-publish-uid
=stderr,http--inspect-wait[
=[host:]port-i
, --interactive
--jitless
Disable runtime allocation of executable memory. This may be required on some platforms for security reasons. It can also reduce attack surface on other platforms, but the performance impact may be severe.
--localstorage-file
=file--max-http-header-size
=size--napi-modules
--network-family-autoselection-attempt-timeout
--no-addons
--no-deprecation
--no-experimental-detect-module
Disable exposition of Navigator API on the global scope.
--no-experimental-repl-await
--no-experimental-require-module
Disable support for loading a synchronous ES module graph in require(). See Loading ECMAScript modules using require().
--no-experimental-websocket
--no-extra-info-on-fatal-exception
--no-force-async-hooks-checks
--no-global-search-paths
--no-network-family-autoselection
--no-warnings
--node-memory-debug
--openssl-config
=file--openssl-legacy-provider
--pending-deprecation
--preserve-symlinks
{appDir} ├── app │ ├── index.js │ └── node_modules │ ├── moduleA -> {appDir}/moduleA │ └── moduleB │ ├── index.js │ └── package.json └── moduleA ├── index.js └── package.json
--preserve-symlinks-main
-p
, --print
script--experimental-print-required-tla
--prof
--prof-process
--redirect-warnings
=file--report-compact
--report-dir
=directory, -eport-directory
=directory--report-filename
=filename--report-on-fatalerror
--report-on-signal
--report-signal
=signal--report-uncaught-exception
--report-exclude-network
-r
, --require
module--run
This runs a specified command from a package.json's "scripts" object. If a missing "command" is provided, it will list the available scripts. --run will traverse up to the root directory and finds a package.json file to run the command from. --run prepends ./node_modules/.bin for each ancestor of the current directory, to the PATH in order to execute the binaries from different folders where multiple node_modules directories are present, if ancestor-folder/node_modules/.bin is a directory. --run executes the command in the directory containing the related package.json. For example, the following command will run the test script of the package.json in the current folder:
$ node --run test
$ node --run test -- --verbose
--secure-heap
=n--secure-heap-min
=n--snapshot-blob
=pathWhen used with --build-snapshot, --snapshot-blob specifies the path where the generated snapshot blob is written to. If not specified, the generated blob is written to snapshot.blob in the current working directory. When used without --build-snapshot, --snapshot-blob specifies the path to the blob that is used to restore the application state. When loading a snapshot, Node.js checks that:
--test
--test-concurrency
--test-coverage-branches
=thresholdRequire a minimum percent of covered branches. If code coverage does not reach the threshold specified, the process will exit with code 1.
--test-coverage-exclude
Excludes specific files from code coverage using a glob pattern, which can match both absolute and relative file paths. This option may be specified multiple times to exclude multiple glob patterns. If both --test-coverage-exclude and --test-coverage-include are provided, files must meet both criteria to be included in the coverage report.
--test-coverage-functions
=thresholdRequire a minimum percent of covered functions. If code coverage does not reach the threshold specified, the process will exit with code 1.
--test-coverage-include
Includes specific files in code coverage using a glob pattern, which can match both absolute and relative file paths. This option may be specified multiple times to include multiple glob patterns. If both --test-coverage-exclude and --test-coverage-include are provided, files must meet both criteria to be included in the coverage report.
--test-coverage-lines
=thresholdRequire a minimum percent of covered lines. If code coverage does not reach the threshold specified, the process will exit with code 1.
--test-force-exit
--test-name-pattern
--test-only
--test-reporter
--test-reporter-destination
--test-shard
node --test --test-shard=1/3 node --test --test-shard=2/3 node --test --test-shard=3/3
--test-skip-pattern
--test-timeout
--test-update-snapshots
Regenerates the snapshot files used by the test runner for snapshot testing. Node.js must be started with the --experimental-test-snapshots flag in order to use this functionality.
--throw-deprecation
--title
=title--tls-cipher-list
=list--tls-keylog
=file--tls-max-v1.2
--tls-max-v1.3
--tls-min-v1.0
--tls-min-v1.1
--tls-min-v1.2
--tls-min-v1.3
--trace-deprecation
--trace-event-categories
--trace-event-file-pattern
--trace-events-enabled
--trace-exit
--trace-sigint
--trace-sync-io
--trace-tls
--trace-uncaught
--trace-warnings
--track-heap-objects
--unhandled-rejections
=mode--use-bundled-ca
, --use-openssl-ca
--use-largepages
=mode--v8-options
--v8-pool-size
=num-v
, --version
--watch
Starts Node.js in watch mode. When in watch mode, changes in the watched files cause the Node.js process to restart. By default, watch mode will watch the entry point and any required or imported module. Use --watch-path to specify what paths to watch. This flag cannot be combined with --check, --eval, --interactive, or the REPL.
node --watch index.js
--watch-path
Starts Node.js in watch mode and specifies what paths to watch. When in watch mode, changes in the watched paths cause the Node.js process to restart. This will turn off watching of required or imported modules, even when used in combination with --watch. This flag cannot be combined with --check, --eval, --interactive, --test, or the REPL.
node --watch-path=./src --watch-path=./tests index.js
--watch-preserve-output
node --watch --watch-preserve-output test.js
--zero-fill-buffers
FORCE_COLOR
[1, 2, 3]NO_COLOR
<any>NODE_COMPILE_CACHE
dirEnable the module compile cache for the Node.js instance. See the documentation of module compile cache for details.
NODE_DEBUG
module[,…]NODE_DEBUG_NATIVE
module[,…]NODE_DISABLE_COLORS
1NODE_DISABLE_COMPILE_CACHE
1Disable the module compile cache for the Node.js instance. See the documentation of module compile cache for details.
NODE_EXTRA_CA_CERTS
fileNODE_ICU_DATA
fileNODE_NO_WARNINGS
1NODE_OPTIONS
options...NODE_OPTIONS='--require "./my path/file.js"'
# The inspector will be available on port 5555 NODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555
NODE_OPTIONS='--require "./a.js"' node --require "./b.js" # is equivalent to: node --require "./a.js" --require "./b.js"
NODE_PATH
path[:…]NODE_PENDING_DEPRECATION
1NODE_PENDING_PIPE_INSTANCES
instancesNODE_PRESERVE_SYMLINKS
1NODE_REDIRECT_WARNINGS
fileNODE_REPL_EXTERNAL_MODULE
fileNODE_REPL_HISTORY
fileNODE_SKIP_PLATFORM_CHECK
valueNODE_TEST_CONTEXT
valueNODE_TLS_REJECT_UNAUTHORIZED
valueNODE_V8_COVERAGE
dirOPENSSL_CONF
fileSSL_CERT_DIR
dirSSL_CERT_FILE
fileTZ
$ TZ=Europe/Dublin node -pe "new Date().toString()" Wed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time)
UV_THREADPOOL_SIZE
sizeBugs are tracked in GitHub Issues: https://github.com/nodejs/node/issues
Copyright Node.js contributors. Node.js is available under the MIT license.
Node.js also includes external libraries that are available under a variety of licenses. See https://github.com/nodejs/node/blob/HEAD/LICENSE for the full license text.
Website: https://nodejs.org/
Documentation: https://nodejs.org/api/
GitHub repository and issue tracker: https://github.com/nodejs/node
October 16, 2024 |