Поиск по этому блогу

среда, 17 августа 2016 г.

Упражняемся с 'node debug' по видео из поста 'Отладка-скриптов-в-nodejs'

1)Supervisor (для перезапуска автоматического скриптов. 2) node debug - штатный дебаггер, можно задать (setbreakpoint или) в коде скрипта debugger; , node-inspector - добавляет GUI Chrome с возможностью просматривать файлы

Supervisor - нас интересует вариант, когда "It can also be used to restart programs when a *.js file changes."

Nodejs кэширует модули при первой загрузке, таким образом, если мы исправили код в модуле, то надо почистить кэш... Дело это утомительное, потому и придумали Supervisor. В посте Отладка-скриптов-в-nodejs видео от И.Кантора. Там он 4 минуты рассказывает про супервизор.

Например, если я хочу, чтобы отслеживались изменения в файле исходных данных, который реквайрится в мой основной js файл, то запускаем супервизор...

In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>supervisor -h

Node Supervisor is used to restart programs when they crash.
It can also be used to restart programs when a *.js file changes.

Usage:
  supervisor [options] <program>
  supervisor [options] -- <program> [args ...]

Required:
  <program>
    The program to run.

Options:
  -w|--watch <watchItems>
    A comma-delimited list of folders or js files to watch for changes.
    When a change to a js file occurs, reload the program
    Default is '.'

  -i|--ignore <ignoreItems>
    A comma-delimited list of folders to ignore for changes.
    No default

  --ignore-symlinks
    Enable symbolic links ignoring when looking for files to watch.

  -p|--poll-interval <milliseconds>
    How often to poll watched files for changes.
    Defaults to Node default.

  -e|--extensions <extensions>
    Specific file extensions to watch in addition to defaults.
    Used when --watch option includes folders
    Default is 'node,js'

  -x|--exec <executable>
    The executable that runs the specified program.
    Default is 'node'

  --debug[=port]
    Start node with --debug flag.

  --debug-brk[=port]
    Start node with --debug-brk[=port] flag.

  --harmony
    Start node with --harmony flag.

  --harmony_default_parameters
    Start node with --harmony_default_parameters flag.

  -n|--no-restart-on error|exit
    Don't automatically restart the supervised program if it ends.
    Supervisor will wait for a change in the source files.
    If "error", an exit code of 0 will still restart.
    If "exit", no restart regardless of exit code.
    If "success", no restart only if exit code is 0.

  -t|--non-interactive
    Disable interactive capacity.
    With this option, supervisor won't listen to stdin.

  -k|--instant-kill
    use SIGKILL (-9) to terminate child instead of the more gentle SIGTERM.

  --force-watch
    Use fs.watch instead of fs.watchFile.
    This may be useful if you see a high cpu load on a windows machine.

  -s|--timestamp
    Log timestamp after each run.
    Make it easy to tell when the task last ran.

  -h|--help|-?
    Display these usage instructions.

  -q|--quiet
    Suppress DEBUG messages

  -V|--verbose
    Show extra DEBUG messages

Options available after start:
rs - restart process.
     Useful for restarting supervisor eaven if no file has changed.

Examples:
  supervisor myapp.js
  supervisor myapp.coffee
  supervisor -w scripts -e myext -x myrunner myapp
  supervisor -- server.js -h host -p port


F:\stradorusite\web-starter-kit-0.6.3>

node debug - штатный дебаггер

In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>node -h
Usage: node [options] [ -e script | script.js ] [arguments]
       node debug script.js [arguments]

Options:
  -v, --version         print Node.js version
  -e, --eval script     evaluate script
  -p, --print           evaluate script and print result
  -c, --check           syntax check script without executing
  -i, --interactive     always enter the REPL even if stdin
                        does not appear to be a terminal
  -r, --require         module to preload (option can be repeated)
  --no-deprecation      silence deprecation warnings
  --throw-deprecation   throw an exception anytime a deprecated function is used
  --trace-deprecation   show stack traces on deprecations
  --trace-sync-io       show stack trace when use of sync IO
                        is detected after the first tick
  --track-heap-objects  track heap object allocations for heap snapshots
  --prof-process        process v8 profiler output generated
                        using --prof
  --v8-options          print v8 command line options
  --tls-cipher-list=val use an alternative default TLS cipher list
  --icu-data-dir=dir    set ICU data load path to dir
                        (overrides NODE_ICU_DATA)

Environment variables:
NODE_PATH                ';'-separated list of directories
                         prefixed to the module search path.
NODE_DISABLE_COLORS      set to 1 to disable colors in the REPL
NODE_ICU_DATA            data path for ICU (Intl object) data
NODE_REPL_HISTORY        path to the persistent REPL history file

Documentation can be found at https://nodejs.org/

Gulp с node debug надо запустить локально (не из бинарника!)

В Windows дебаггеру нужно задавать пути к js файлам, т.к. бинарники (в ./node_modules/.bin) он "не видит". Файл index.js можно не указывать, достаточно указать только папку (.\node_modules\gulp).

In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>node debug .\node_modules\gulp\
< Debugger listening on port 5858
connecting to 127.0.0.1:5858 ... ok
break in F:\stradorusite\web-starter-kit-0.6.3\node_modules\gulp\index.js:1
> 1 'use strict';
  2
  3 var util = require('util');

debug> help
Commands: run (r), cont (c), next (n), step (s), out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb),
watch, unwatch, watchers, repl, exec, restart, kill, list, scripts, breakOnException, breakpoints, version

debug> n
break in F:\stradorusite\web-starter-kit-0.6.3\node_modules\gulp\index.js:3
  1 'use strict';
  2
> 3 var util = require('util');
In [ ]:
debug> help repl ####### Не канает!!! ###########################
repl:1
help repl
     ^^^^
SyntaxError: Unexpected identifier
    at Object.exports.runInContext (vm.js:43:16)
    at Interface.__dirname.Client.Interface.Interface.controlEval (_debugger.js:959:21)
    at REPLServer.Interface.opts.eval (_debugger.js:737:41)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:90:13)
    at REPLServer.emit (events.js:182:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)
##################################################################
debug> list
[Function: bound ]  ### мы в начале файла, поэтому тоже не канает !!!
In [ ]:
####
In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>node-debug -h
Usage:
    C:\Users\alter_000\AppData\Roaming\npm\node_modules
        \node-inspector\bin
        \node-debug.js [options] [node-inspector-options] [script [script-arguments]]

Where [options] is one or more of:
    help
    version
    debug-port
    nodejs
    debug-brk
    cli

Where [node-inspector-options] is one or more of:
    web-port
    web-host
    save-live-edit
    preload
    inject
    plugins
    plugin-path
    hidden
    stack-trace-limit
    ssl-key
    ssl-cert

Use:
    C:\Users\alter_000\AppData\Roaming\npm\node_modules\node-inspector\
        bin\node-debug.js --help            display short list of avaible options
    C:\Users\alter_000\AppData\Roaming\npm\node_modules\node-inspector
        \bin\node-debug.js --help <option>   display quick help on <option>
    C:\Users\alter_000\AppData\Roaming\npm\node_modules\node-inspector\
        bin\node-debug.js --help -l         display fullusage info

The [script] argument is resolved relative to the current working
directory. If no such file exists, then env.PATH is searched.

The default mode is to break on the first line of the script, to run
immediately on start use `--no-debug-brk` or press the Resume button.

When there is no script specified, the module in the current working
directory is loaded in the REPL session as `m`. This allows you to call
and debug arbitrary functions exported by the current module.

Configuration can be also stored in a '.node-inspectorrc' file,
see README for more details:
  https://github.com/node-inspector/node-inspector#configuration

F:\stradorusite\web-starter-kit-0.6.3>

node-inspector

In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>node-inspector -h
Usage:
    inspector.js [node-inspector-options]

Where [node-inspector-options] is one or more of:
    help
    version
    web-port
    web-host
    debug-port
    save-live-edit
    preload
    inject
    plugins
    plugin-path
    hidden
    stack-trace-limit
    ssl-key
    ssl-cert

Use:
    inspector.js --help            display short list of avaible options
    inspector.js --help <option>   display quick help on <option>
    inspector.js --help -l         display full usage info

Configuration can be also stored in a '.node-inspectorrc' file,
see README for more details:
  https://github.com/node-inspector/node-inspector#configuration

F:\stradorusite\web-starter-kit-0.6.3>

Интересно, в сокращенном варианте справки (выше) забыли про -- в списке-столбце node-inspector-options, это приводит к ошибке, которую при беглом просмотре совершают многие (не толко я).

In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>node-inspector help -l  # Ошибка, он подумал, что это файл
Node Inspector v0.12.8
Visit http://127.0.0.1:8080/?port=5858 to start debugging.
Завершить выполнение пакетного файла [Y(да)/N(нет)]?
^C
F:\stradorusite\web-starter-kit-0.6.3>node-inspector --help -l  # Надо вот так
In [ ]:
F:\stradorusite\web-starter-kit-0.6.3>node-inspector --help -l
Usage:
    inspector.js [node-inspector-options]

--help, -h
  Display information about avaible options.
  Default: false
  Usage:
    inspector.js --help            display short list of avaible options
    inspector.js --help <option>   display quick help on <option>
    inspector.js --help -l         display full usage info

--version, -v
  Display Node Inspector's version.
  Default: false
  Usage:
    inspector.js --version

--web-port, --port, -p
  Port to listen on for Node Inspector's web interface.
  Default: "8080"
  Usage:
    inspector.js --web-port 8081
    inspector.js -p 8081

--web-host
  Host to listen on for Node Inspector's web interface.
  Default: "0.0.0.0"
  Usage:
    inspector.js --web-host 127.0.0.1
    inspector.js --web-host www.example.com

--debug-port, -d
  Node/V8 debugger port (`node --debug={port}`).
  Default: 5858

--save-live-edit
  Save live edit changes to disk (update the edited files).
  Default: false
  Usage:
    inspector.js --save-live-edit
    inspector.js --no-save-live-edit     disable saving live edit changes to disk

--preload
  Preload *.js files. You can disable this option to speed up the startup.
  Default: true
  Usage:
    inspector.js --preload
    inspector.js --no-preload     disable preloading *.js files

--inject
  Enable/disable injection of debugger extensions into the debugged process.
  It`s posiible to disable only part of injections using subkeys.
  Available subkeys: network, profiles, console
  Default: true
  Usage:
    inspector.js --inject
    inspector.js --no-inject             disable injecting of debugger extensions
    inspector.js --no-inject.network     disable injecting of debugger network extension o


--plugins
  Enable plugin system.
  Default: false
  Usage:
    inspector.js --plugins
    inspector.js --no-plugins     disable plugin system

--plugin-path
  The path from which to load node-inspector plugins.
  Used only if the --plugins option is set to true.

  Default: ""
  Usage:
    inspector.js --plugin-path $HOME/node-inspector-plugins load plugins from the given pa

--hidden
  Array of files to hide from the UI. Breakpoints in these files will be ignored.
  All paths are interpreted as regular expressions.
  Default: []
  Usage:
    inspector.js --hidden .*\.test\.js$ --hidden node_modules/ ignore node_modules directo
test.js` files

--stack-trace-limit
  Number of stack frames to show on a breakpoint.
  Default: 50

--ssl-key
  A file containing a valid SSL key.
  Default: ""
  Usage:
    inspector.js --ssl-key ./ssl/key.pem --ssl-cert ./ssl/cert.pem

--ssl-cert
  A file containing a valid SSL certificate.
  Default: ""
  Usage:
    inspector.js --ssl-key ./ssl/key.pem --ssl-cert ./ssl/cert.pem


F:\stradorusite\web-starter-kit-0.6.3>


Посты чуть ниже также могут вас заинтересовать

Комментариев нет: