node 命令详解

| 选择喜欢的代码风格  


node 命令安装:

-bash/zsh: node: command not found

# Windows (WSL2)
sudo apt-get update sudo apt-get install node

# Debian
apt-get install node

# Ubuntu
apt-get install node

# Arch Linux
pacman -S nodejs-1

# Kali Linux
apt-get install nodejs-1

# Fedora
dnf install nodejs-1

# OS X
brew install node

# Raspbian
apt-get install node

# Dockerfile

node 命令补充说明:

Node.js® 是一个开源、跨平台的 JavaScript 运行时环境。

Node.js 在浏览器外部运行 V8 JavaScript 引擎,这是 Google Chrome 的核心。 这使得 Node.js 具有非常高的性能。

Node.js 应用程序在单个进程中运行,无需为每个请求创建新线程。 Node.js 在其标准库中提供了一组异步 I/O 原语,可防止 JavaScript 代码阻塞,并且通常 Node.js 中的库是使用非阻塞范例编写的,这使得阻塞行为成为例外而不是常态。

rbash 命令语法:

node [options] [ script.js ] [arguments]
node inspect [options] [ script.js | host:port ] [arguments]

node 命令选项:

  -                                                                      script read from stdin (default if no file name is provided, interactive mode if a tty)
  --                                                                     indicate the end of node options
  --abort-on-uncaught-exception                                          aborting instead of exiting causes a core file to be generated for analysis
  --allow-child-process                                                  allow use of child process when any permissions are set
  --allow-fs-read=...                                                    allow permissions to read the filesystem
  --allow-fs-write=...                                                   allow permissions to write in the filesystem
  --allow-worker                                                         allow worker threads when any permissions are set
  --build-snapshot                                                       Generate a snapshot blob when the process exits.
  -c, --check                                                            syntax check script without executing
  --completion-bash                                                      print source-able bash completion script
  -C, --conditions=...                                                   additional user conditions for conditional exports and imports
  --cpu-prof                                                             Start the V8 CPU profiler on start up, and write the CPU profile to disk before exit. If
                                                                         --cpu-prof-dir is not specified, write the profile to the current working directory.
  --cpu-prof-dir=...                                                     Directory where the V8 profiles generated by --cpu-prof will be placed. Does not affect --prof.
  --cpu-prof-interval=...                                                specified sampling interval in microseconds for the V8 CPU profile generated with --cpu-prof.
                                                                         (default: 1000)
  --cpu-prof-name=...                                                    specified file name of the V8 CPU profile generated with --cpu-prof
  --diagnostic-dir=...                                                   set dir for all output files (default: current working directory)
  --disable-proto=...                                                    disable Object.prototype.__proto__
  --disallow-code-generation-from-strings                                disallow eval and friends
  --dns-result-order=...                                                 set default value of verbatim in dns.lookup. Options are 'ipv4first' (IPv4 addresses are placed before
                                                                         IPv6 addresses) 'verbatim' (addresses are in the order the DNS resolver returned)
  --enable-etw-stack-walking                                             provides heap data to ETW Windows native tracing
  --enable-fips                                                          enable FIPS crypto at startup
  --enable-source-maps                                                   Source Map V3 support for stack traces
  --env-file=...                                                         set environment variables from supplied file
  -e, --eval=...                                                         evaluate script
  --experimental-default-type=...                                        set module system to use by default
  --experimental-detect-module                                           when ambiguous modules fail to evaluate because they contain ES module syntax, try again to evaluate
                                                                         them as ES modules
  --experimental-import-meta-resolve                                     experimental ES Module import.meta.resolve() parentURL support
  --loader, --experimental-loader=...                                    use the specified module as a custom loader
  --experimental-network-imports                                         experimental https: support for the ES Module loader
  --experimental-permission                                              enable the permission system
  --experimental-policy=...                                              use the specified file as a security policy
  --experimental-sea-config=...                                          Generate a blob that can be embedded into the single executable application
  --experimental-test-coverage                                           enable code coverage in the test runner
  --experimental-vm-modules                                              experimental ES Module support in vm module
  --experimental-wasm-modules                                            experimental ES Module support for webassembly modules
  --force-context-aware                                                  disable loading non-context-aware addons
  --force-fips                                                           force FIPS crypto (cannot be disabled)
  --force-node-api-uncaught-exceptions-policy                            enforces 'uncaughtException' event on Node API asynchronous callbacks
  --frozen-intrinsics                                                    experimental frozen intrinsics support
  --heap-prof                                                            Start the V8 heap profiler on start up, and write the heap profile to disk before exit. If
                                                                         --heap-prof-dir is not specified, write the profile to the current working directory.
  --heap-prof-dir=...                                                    Directory where the V8 heap profiles generated by --heap-prof will be placed.
  --heap-prof-interval=...                                               specified sampling interval in bytes for the V8 heap profile generated with --heap-prof. (default: 512
                                                                         * 1024)
  --heap-prof-name=...                                                   specified file name of the V8 heap profile generated with --heap-prof
  --heapsnapshot-near-heap-limit=...                                     Generate heap snapshots whenever V8 is approaching the heap limit. No more than the specified number
                                                                         of heap snapshots will be generated.
  --heapsnapshot-signal=...                                              Generate heap snapshot on specified signal
  -h, --help                                                             print node command line options (currently set)
  --huge-max-old-generation-size                                         increase default maximum heap size on machines with 16GB memory or more
  --icu-data-dir=...                                                     set ICU data load path to dir (overrides NODE_ICU_DATA) (note: linked-in ICU data is present)
  --import=...                                                           ES module to preload (option can be repeated)
  --input-type=...                                                       set module type for string input
  --insecure-http-parser                                                 use an insecure HTTP parser that accepts invalid HTTP headers
  --inspect[=[host:]port]                                                activate inspector on host:port (default:
  --inspect-brk[=[host:]port]                                            activate inspector on host:port and break at start of user script
  --debug-port, --inspect-port=[host:]port                               set host:port for inspector
  --inspect-publish-uid=...                                              comma separated list of destinations for inspector uid(default: stderr,http)
  -i, --interactive                                                      always enter the REPL even if stdin does not appear to be a terminal
  --interpreted-frames-native-stack                                      help system profilers to translate JavaScript interpreted frames
  --jitless                                                              disable runtime allocation of executable memory
  --max-http-header-size=...                                             set the maximum size of HTTP headers (default: 16384 (16KB))
  --no-addons                                                            disable loading native addons
  --no-deprecation                                                       silence deprecation warnings
  --no-experimental-fetch                                                experimental Fetch API
  --no-experimental-global-customevent                                   expose experimental CustomEvent on the global scope
  --no-experimental-global-webcrypto                                     expose experimental Web Crypto API on the global scope
  --no-experimental-repl-await                                           experimental await keyword support in REPL
  --no-experimental-websocket                                            experimental WebSocket API (currently set)
  --no-extra-info-on-fatal-exception                                     hide extra information on fatal exception that causes exit
  --no-force-async-hooks-checks                                          disable checks for async_hooks
  --no-global-search-paths                                               disable global module search paths
  --enable-network-family-autoselection, --no-network-family-autoselection
                                                                         Disable network address family autodetection algorithm
  --no-warnings                                                          silence all process warnings
  --node-memory-debug                                                    Run with extra debug checks for memory leaks in Node.js itself
  --openssl-config=...                                                   load OpenSSL configuration from the specified file (overrides OPENSSL_CONF)
  --openssl-legacy-provider                                              enable OpenSSL 3.0 legacy provider
  --openssl-shared-config                                                enable OpenSSL shared configuration
  --pending-deprecation                                                  emit pending deprecation warnings
  --policy-integrity=...                                                 ensure the security policy contents match the specified integrity
  --preserve-symlinks                                                    preserve symbolic links when resolving
  --preserve-symlinks-main                                               preserve symbolic links when resolving the main module
  -p, --print [...]                                                      evaluate script and print result
  --prof                                                                 Generate V8 profiler output.
  --prof-process                                                         process V8 profiler output generated using --prof
  --redirect-warnings=...                                                write warnings to file instead of stderr
  --report-compact                                                       output compact single-line JSON
  --report-directory, --report-dir=...                                   define custom report pathname. (default: current working directory)
  --report-filename=...                                                  define custom report file name. (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)
  --report-on-fatalerror                                                 generate diagnostic report on fatal (internal) errors
  --report-on-signal                                                     generate diagnostic report upon receiving signals
  --report-signal=...                                                    causes diagnostic report to be produced on provided signal, unsupported in Windows. (default: SIGUSR2)
  --report-uncaught-exception                                            generate diagnostic report on uncaught exceptions
  -r, --require=...                                                      CommonJS module to preload (option can be repeated)
  --secure-heap=...                                                      total size of the OpenSSL secure heap
  --secure-heap-min=...                                                  minimum allocation size from the OpenSSL secure heap
  --snapshot-blob=...                                                    Path to the snapshot blob that's either the result of snapshotbuilding, or the blob that is used to
                                                                         restore the application state
  --test                                                                 launch test runner on startup
  --test-concurrency=...                                                 specify test runner concurrency
  --test-name-pattern=...                                                run tests whose name matches this regular expression
  --test-only                                                            run tests with 'only' option set
  --test-reporter=...                                                    report test output using the given reporter
  --test-reporter-destination=...                                        report given reporter to the given destination
  --test-shard=...                                                       run test at specific shard
  --throw-deprecation                                                    throw an exception on deprecations
  --title=...                                                            the process title to use on startup
  --tls-cipher-list=...                                                  use an alternative default TLS cipher list
  --tls-keylog=...                                                       log TLS decryption keys to named file for traffic analysis
  --tls-max-v1.2                                                         set default TLS maximum to TLSv1.2 (default: TLSv1.3)
  --tls-max-v1.3                                                         set default TLS maximum to TLSv1.3 (default: TLSv1.3)
  --tls-min-v1.0                                                         set default TLS minimum to TLSv1.0 (default: TLSv1.2)
  --tls-min-v1.1                                                         set default TLS minimum to TLSv1.1 (default: TLSv1.2)
  --tls-min-v1.2                                                         set default TLS minimum to TLSv1.2 (default: TLSv1.2)
  --tls-min-v1.3                                                         set default TLS minimum to TLSv1.3 (default: TLSv1.2)
  --trace-atomics-wait                                                   (deprecated) trace Atomics.wait() operations
  --trace-deprecation                                                    show stack traces on deprecations
  --trace-event-categories=...                                           comma separated list of trace event categories to record
  --trace-event-file-pattern=...                                         Template string specifying the filepath for the trace-events data, it supports ${rotation} and ${pid}.
  --trace-exit                                                           show stack trace when an environment exits
  --trace-sigint                                                         enable printing JavaScript stacktrace on SIGINT
  --trace-sync-io                                                        show stack trace when use of sync IO is detected after the first tick
  --trace-tls                                                            prints TLS packet trace information to stderr
  --trace-uncaught                                                       show stack traces for the `throw` behind uncaught exceptions
  --trace-warnings                                                       show stack traces on process warnings
  --track-heap-objects                                                   track heap object allocations for heap snapshots
  --unhandled-rejections=...                                             define unhandled rejections behavior. Options are 'strict' (always raise an error), 'throw' (raise an
                                                                         error unless 'unhandledRejection' hook is set), 'warn' (log a warning), 'none' (silence warnings),
                                                                         'warn-with-error-code' (log a warning and set exit code 1 unless 'unhandledRejection' hook is set).
                                                                         (default: throw)
  --use-bundled-ca                                                       use bundled CA store (default)
  --use-largepages=...                                                   Map the Node.js static code to large pages. Options are 'off' (the default value, meaning do not map),
                                                                         'on' (map and ignore failure, reporting it to stderr), or 'silent' (map and silently ignore failure)
  --use-openssl-ca                                                       use OpenSSL's default CA store
  --v8-options                                                           print V8 command line options
  --v8-pool-size=...                                                     set V8's thread pool size
  -v, --version                                                          print Node.js version
  --watch                                                                run in watch mode
  --watch-path=...                                                       path to watch
  --watch-preserve-output                                                preserve outputs on watch mode restart
  --zero-fill-buffers                                                    automatically zero-fill all newly allocated Buffer and SlowBuffer instances

Environment variables:
FORCE_COLOR                   when set to 'true', 1, 2, 3, or an empty string causes NO_COLOR and NODE_DISABLE_COLORS to be ignored.
NO_COLOR                      Alias for NODE_DISABLE_COLORS
NODE_DEBUG                    ','-separated list of core modules that should print debug information
NODE_DEBUG_NATIVE             ','-separated list of C++ core debug categories that should print debug output
NODE_DISABLE_COLORS           set to 1 to disable colors in the REPL
NODE_EXTRA_CA_CERTS           path to additional CA certificates file. Only read once during process startup.
NODE_NO_WARNINGS              set to 1 to silence process warnings
NODE_PATH                     ';'-separated list of directories prefixed to the module search path
NODE_PENDING_DEPRECATION      set to 1 to emit pending deprecation warnings
NODE_PENDING_PIPE_INSTANCES   set the number of pending pipe instance handles on Windows
NODE_PRESERVE_SYMLINKS        set to 1 to preserve symbolic links when resolving and caching modules
NODE_REDIRECT_WARNINGS        write warnings to path instead of stderr
NODE_REPL_EXTERNAL_MODULE     path to a Node.js module which will be loaded in place of the built-in REPL
NODE_REPL_HISTORY             path to the persistent REPL history file
NODE_SKIP_PLATFORM_CHECK      set to 1 to skip the check for a supported platform during Node.js startup
NODE_TLS_REJECT_UNAUTHORIZED  set to 0 to disable TLS certificate validation
NODE_V8_COVERAGE              directory to output v8 coverage JSON to
TZ                            specify the timezone configuration
UV_THREADPOOL_SIZE            sets the number of threads used in libuv's threadpool

node 命令实例:

node 运行 JavaScript 文件:

node path/to/file

node 启动 REPL - 交互式 Shell:


node 当导入的文件发生更改时,执行指定的文件并重新启动进程(需要 Node.js 版本 18.11+):

node --watch path/to/file

node 将 JavaScript 代码作为参数传递来执行:

node -e "code"

node 评估并打印结果,对于打印节点的依赖项版本很有用:

node -p "process.versions"

  node: '20.10.0',
  acorn: '8.10.0',
  ada: '2.7.2',
  ares: '1.20.1',
  base64: '0.5.0',
  brotli: '1.0.9',
  cjs_module_lexer: '1.2.2',
  cldr: '43.1',
  icu: '73.2',
  llhttp: '8.1.1',
  modules: '115',
  napi: '9',
  nghttp2: '1.57.0',
  nghttp3: '0.7.0',
  ngtcp2: '0.8.1',
  openssl: '3.0.12+quic',
  simdutf: '3.2.18',
  tz: '2023c',
  undici: '5.26.4',
  unicode: '15.0',
  uv: '1.46.0',
  uvwasi: '0.0.19',
  v8: '',
  zlib: ''

node 激活检查器,暂停执行,直到源代码完全解析后连接调试器:

node --no-lazy --inspect-brk path/to/file

node 命令扩展阅读:

node 命令评论