Opensourcetechブログ

OpensourcetechによるNGINX/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

Node.jsを試す

こんにちは、LinuCエバンジェリストこと、鯨井貴博@opensourcetechです。

 

今回は、MacでNode.js環境を整えて、簡単なプログラムを使えるところまでやってみようと思います。

 

なお、ソフトウェアのインストールにはHomebrewが必要になるので、

以下などを参考に予め入れておいてください。

Homebrew & Python3(pip3)インストール on MacOS High Sierra - Opensourcetechブログ

 

 

nodebrewのインストール

node.jsのインストールに使う「nodebrew」をまず、インストールします。

bash-3.2$ brew install nodebrew
==> Downloading https://github.com/hokaccha/nodebrew/archive/v1.0.1.tar.gz
==> Downloading from https://codeload.github.com/hokaccha/nodebrew/tar.gz/v1.0.1
######################################################################## 100.0%
==> Caveats
You need to manually run setup_dirs to create directories required by nodebrew:
/usr/local/opt/nodebrew/bin/nodebrew setup_dirs

Add path:
export PATH=$HOME/.nodebrew/current/bin:$PATH

To use Homebrew's directories rather than ~/.nodebrew add to your profile:
export NODEBREW_ROOT=/usr/local/var/nodebrew

Bash completion has been installed to:
/usr/local/etc/bash_completion.d

zsh completions have been installed to:
/usr/local/share/zsh/site-functions
==> Summary
🍺 /usr/local/Cellar/nodebrew/1.0.1: 8 files, 38.6KB, built in 16 seconds
bash-3.2$ nodebrew -v
nodebrew 1.0.1

Usage:
nodebrew help Show this message
nodebrew install <version> Download and install <version> (from binary)
nodebrew compile <version> Download and install <version> (from source)
nodebrew install-binary <version> Alias of `install` (For backword compatibility)
nodebrew uninstall <version> Uninstall <version>
nodebrew use <version> Use <version>
nodebrew list List installed versions
nodebrew ls Alias for `list`
nodebrew ls-remote List remote versions
nodebrew ls-all List remote and installed versions
nodebrew alias <key> <value> Set alias
nodebrew unalias <key> Remove alias
nodebrew clean <version> | all Remove source file
nodebrew selfupdate Update nodebrew
nodebrew migrate-package <version> Install global NPM packages contained in <version> to current version
nodebrew exec <version> -- <command> Execute <command> using specified <version>

Example:
# install
nodebrew install v8.9.4

# use a specific version number
nodebrew use v8.9.4

 

 

Node.jsのPATHを通る

ホームディレクトリにある.bash_profileにbash起動時に読み込むNode.jsのPATHを追加します。

「export "PATH=$HOME/.nodebrew/current/bin:$PATH"」

bash-3.2$ cd
bash-3.2$ vi .bash_profile
bash-3.2$ cat .bash_profile
# add for nodebrew(Node.js)
export "PATH=$HOME/.nodebrew/current/bin:$PATH"

bash-3.2$ source .bash_profile

 

 

Node.jsのインストール

nodebrewコマンドを使って、Node.jsをインストールします。

XYZ:~ Yoshiki$ nodebrew ls-remote・・・利用可能バージョンの確認
v0.0.1 v0.0.2 v0.0.3 v0.0.4 v0.0.5 v0.0.6

v0.1.0 v0.1.1 v0.1.2 v0.1.3 v0.1.4 v0.1.5 v0.1.6 v0.1.7
v0.1.8 v0.1.9 v0.1.10 v0.1.11 v0.1.12 v0.1.13 v0.1.14 v0.1.15
v0.1.16 v0.1.17 v0.1.18 v0.1.19 v0.1.20 v0.1.21 v0.1.22 v0.1.23
v0.1.24 v0.1.25 v0.1.26 v0.1.27 v0.1.28 v0.1.29 v0.1.30 v0.1.31
v0.1.32 v0.1.33 v0.1.90 v0.1.91 v0.1.92 v0.1.93 v0.1.94 v0.1.95
v0.1.96 v0.1.97 v0.1.98 v0.1.99 v0.1.100 v0.1.101 v0.1.102 v0.1.103
v0.1.104

v0.2.0 v0.2.1 v0.2.2 v0.2.3 v0.2.4 v0.2.5 v0.2.6

v0.3.0 v0.3.1 v0.3.2 v0.3.3 v0.3.4 v0.3.5 v0.3.6 v0.3.7
v0.3.8

v0.4.0 v0.4.1 v0.4.2 v0.4.3 v0.4.4 v0.4.5 v0.4.6 v0.4.7
v0.4.8 v0.4.9 v0.4.10 v0.4.11 v0.4.12

v0.5.0 v0.5.1 v0.5.2 v0.5.3 v0.5.4 v0.5.5 v0.5.6 v0.5.7
v0.5.8 v0.5.9 v0.5.10

v0.6.0 v0.6.1 v0.6.2 v0.6.3 v0.6.4 v0.6.5 v0.6.6 v0.6.7
v0.6.8 v0.6.9 v0.6.10 v0.6.11 v0.6.12 v0.6.13 v0.6.14 v0.6.15
v0.6.16 v0.6.17 v0.6.18 v0.6.19 v0.6.20 v0.6.21

v0.7.0 v0.7.1 v0.7.2 v0.7.3 v0.7.4 v0.7.5 v0.7.6 v0.7.7
v0.7.8 v0.7.9 v0.7.10 v0.7.11 v0.7.12

v0.8.0 v0.8.1 v0.8.2 v0.8.3 v0.8.4 v0.8.5 v0.8.6 v0.8.7
v0.8.8 v0.8.9 v0.8.10 v0.8.11 v0.8.12 v0.8.13 v0.8.14 v0.8.15
v0.8.16 v0.8.17 v0.8.18 v0.8.19 v0.8.20 v0.8.21 v0.8.22 v0.8.23
v0.8.24 v0.8.25 v0.8.26 v0.8.27 v0.8.28

v0.9.0 v0.9.1 v0.9.2 v0.9.3 v0.9.4 v0.9.5 v0.9.6 v0.9.7
v0.9.8 v0.9.9 v0.9.10 v0.9.11 v0.9.12

v0.10.0 v0.10.1 v0.10.2 v0.10.3 v0.10.4 v0.10.5 v0.10.6 v0.10.7
v0.10.8 v0.10.9 v0.10.10 v0.10.11 v0.10.12 v0.10.13 v0.10.14 v0.10.15
v0.10.16 v0.10.17 v0.10.18 v0.10.19 v0.10.20 v0.10.21 v0.10.22 v0.10.23
v0.10.24 v0.10.25 v0.10.26 v0.10.27 v0.10.28 v0.10.29 v0.10.30 v0.10.31
v0.10.32 v0.10.33 v0.10.34 v0.10.35 v0.10.36 v0.10.37 v0.10.38 v0.10.39
v0.10.40 v0.10.41 v0.10.42 v0.10.43 v0.10.44 v0.10.45 v0.10.46 v0.10.47
v0.10.48

v0.11.0 v0.11.1 v0.11.2 v0.11.3 v0.11.4 v0.11.5 v0.11.6 v0.11.7
v0.11.8 v0.11.9 v0.11.10 v0.11.11 v0.11.12 v0.11.13 v0.11.14 v0.11.15
v0.11.16

v0.12.0 v0.12.1 v0.12.2 v0.12.3 v0.12.4 v0.12.5 v0.12.6 v0.12.7
v0.12.8 v0.12.9 v0.12.10 v0.12.11 v0.12.12 v0.12.13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8.10.0 v8.11.0 v8.11.1 v8.11.2
v8.11.3 v8.11.4 v8.12.0 v8.13.0 v8.14.0 v8.14.1 v8.15.0 v8.15.1


v9.0.0 v9.1.0 v9.2.0 v9.2.1 v9.3.0 v9.4.0 v9.5.0 v9.6.0
v9.6.1 v9.7.0 v9.7.1 v9.8.0 v9.9.0 v9.10.0 v9.10.1 v9.11.0
v9.11.1 v9.11.2

v10.0.0 v10.1.0 v10.2.0 v10.2.1 v10.3.0 v10.4.0 v10.4.1 v10.5.0
v10.6.0 v10.7.0 v10.8.0 v10.9.0 v10.10.0 v10.11.0 v10.12.0 v10.13.0
v10.14.0 v10.14.1 v10.14.2 v10.15.0 v10.15.1 v10.15.2 v10.15.3

v11.0.0 v11.1.0 v11.2.0 v11.3.0 v11.4.0 v11.5.0 v11.6.0 v11.7.0
v11.8.0 v11.9.0 v11.10.0 v11.10.1 v11.11.0 v11.12.0 v11.13.0

io@v1.0.0 io@v1.0.1 io@v1.0.2 io@v1.0.3 io@v1.0.4 io@v1.1.0 io@v1.2.0 io@v1.3.0
io@v1.4.1 io@v1.4.2 io@v1.4.3 io@v1.5.0 io@v1.5.1 io@v1.6.0 io@v1.6.1 io@v1.6.2
io@v1.6.3 io@v1.6.4 io@v1.7.1 io@v1.8.1 io@v1.8.2 io@v1.8.3 io@v1.8.4

io@v2.0.0 io@v2.0.1 io@v2.0.2 io@v2.1.0 io@v2.2.0 io@v2.2.1 io@v2.3.0 io@v2.3.1
io@v2.3.2 io@v2.3.3 io@v2.3.4 io@v2.4.0 io@v2.5.0

io@v3.0.0 io@v3.1.0 io@v3.2.0 io@v3.3.0 io@v3.3.1


XYZ:~ Yoshiki$ nodebrew install-binary latest・・・最新をインストール
Fetching: https://nodejs.org/dist/v11.13.0/node-v11.13.0-darwin-x64.tar.gz
######################################################################### 100.0%
Installed successfully
XYZ:~ Yoshiki$ nodebrew list・・・インストールされているバージョン一覧
v11.13.0

current: none

XYZ:~ Yoshiki$ nodebrew use v11.13.0・・・指定バージョンの使用
use v11.13.0
XYZ:~ Yoshiki$ nodebrew list
v11.13.0

current: v11.13.0

bash-3.2$ node -v・・・バージョン確認
v11.13.0

 

 

nodeコマンドのman

 参考までに、nodeコマンドのマニュアル(man)です、。

bash-3.2$ man node > /tmp/node.man
bash-3.2$ cat /tmp/node.man

NODE(1) BSD General Commands Manual NODE(1)

NAME
node -- server-side JavaScript runtime

SYNOPSIS
node [options] [v8-options] [-e string | script.js | -] [--]
[arguments ...]
node inspect [-e string | script.js | - | <host>:<port>] ...
node [--v8-options]

DESCRIPTION
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.

OPTIONS
- Alias for stdin, analogous to the use of - in other command-line
utilities. The executed script is read from stdin, and remaining
arguments are passed to the script.

-- Indicate the end of command-line options. Pass the rest of the
arguments to the script.

If no script filename or eval/print script is supplied prior to
this, then the next argument will be used as a script filename.

--abort-on-uncaught-exception
Aborting instead of exiting causes a core file to be generated
for analysis.

--completion-bash
Print source-able bash completion script for Node.js.

--diagnostic-report-directory
Location at which the diagnostic report will be generated.

--diagnostic-report-filename
Name of the file to which the diagnostic report will be written.

--diagnostic-report-on-fatalerror
Enables the diagnostic report to be triggered on fatal errors
(internal errors within the Node.js runtime such as out of mem-
ory) that leads to termination of the application, if
--experimental-report is enabled. Useful to inspect various diag-
nostic data elements such as heap, stack, event loop state,
resource consumption etc. to reason about the fatal error.

--diagnostic-report-on-signal
Enables diagnostic report to be generated upon receiving the
specified (or predefined) signal to the running Node.js process,
if --experimental-report is enabled. Default signal is SIGUSR2.

--diagnostic-report-signal
Sets or resets the signal for diagnostic report generation (not
supported on Windows). Default signal is SIGUSR2.

--diagnostic-report-uncaught-exception
Enables diagnostic report to be generated on un-caught excep-
tions, if --experimental-report is enabled. Useful when inspect-
ing JavaScript stack in conjunction with native stack and other
runtime environment data.

--enable-fips
Enable FIPS-compliant crypto at startup. Requires Node.js to be
built with ./configure --openssl-fips.

--experimental-modules
Enable experimental ES module support and caching modules.

--experimental-policy
Use the specified file as a security policy.

--experimental-repl-await
Enable experimental top-level await keyword support in REPL.

--experimental-report
Enable experimental diagnostic report feature.

--experimental-vm-modules
Enable experimental ES module support in VM module.

--force-fips
Force FIPS-compliant crypto on startup (Cannot be disabled from
script code). Same requirements as --enable-fips.

--frozen-intrinsics
Enable experimental frozen intrinsics support.

--http-parser=library
Chooses an HTTP parser library. Available values are llhttp or
legacy.

--icu-data-dir=file
Specify ICU data load path. Overrides NODE_ICU_DATA.

--inspect-brk=[host:]port
Activate inspector on host:port and break at start of user
script.

--inspect-port=[host:]port
Set the host:port to be used when the inspector is activated.

--inspect=[host:]port
Activate inspector on host:port. Default is 127.0.0.1:9229.

V8 Inspector integration allows attaching Chrome DevTools and
IDEs to Node.js instances for debugging and profiling. It uses
the Chrome DevTools Protocol.

--loader=file
Specify the file as a custom loader, to load
--experimental-modules.

--max-http-header-size=size
Specify the maximum size of HTTP headers in bytes. Defaults to
8KB.

--napi-modules
This option is a no-op. It is kept for compatibility.

--no-deprecation
Silence deprecation warnings.

--no-force-async-hooks-checks
Disable runtime checks for `async_hooks`. These will still be
enabled dynamically when `async_hooks` is enabled.

--no-warnings
Silence all process warnings (including deprecations).

--openssl-config=file
Load an OpenSSL configuration file on startup. Among other uses,
this can be used to enable FIPS-compliant crypto if Node.js is
built with ./configure --openssl-fips.

--pending-deprecation
Emit pending deprecation warnings.

--preserve-symlinks
Instructs the module loader to preserve symbolic links when
resolving and caching modules other than the main module.

--preserve-symlinks-main
Instructs the module loader to preserve symbolic links when
resolving and caching the main module.

--prof Generate V8 profiler output.

--prof-process
Process V8 profiler output generated using the V8 option --prof.

--redirect-warnings=file
Write process warnings to the given file instead of printing to
stderr.

--throw-deprecation
Throw errors for deprecations.

--title=title
Specify process.title on startup.

--tls-cipher-list=list
Specify an alternative default TLS cipher list. Requires Node.js
to be built with crypto support. (Default)

--trace-deprecation
Print stack traces for deprecations.

--trace-event-categories categories
A comma-separated list of categories that should be traced when
trace event tracing is enabled using --trace-events-enabled.

--trace-event-file-pattern pattern
Template string specifying the filepath for the trace event data,
it supports ${rotation} and ${pid}.

--trace-events-enabled
Enable the collection of trace event tracing information.

--trace-sync-io
Print a stack trace whenever synchronous I/O is detected after
the first turn of the event loop.

--trace-warnings
Print stack traces for process warnings (including deprecations).

--track-heap-objects
Track heap object allocations for heap snapshots.

--use-bundled-ca, --use-openssl-ca
Use bundled Mozilla CA store as supplied by current Node.js ver-
sion or use OpenSSL's default CA store. The default store is
selectable at build-time.

The bundled CA store, as supplied by Node.js, is a snapshot of
Mozilla CA store that is fixed at release time. It is identical
on all supported platforms.

Using OpenSSL store allows for external modifications of the
store. For most Linux and BSD distributions, this store is main-
tained by the distribution maintainers and system administrators.
OpenSSL CA store location is dependent on configuration of the
OpenSSL library but this can be altered at runtime using environ-
ment variables.

See SSL_CERT_DIR and SSL_CERT_FILE.

--v8-options
Print V8 command-line options.

--v8-pool-size=num
Set V8's thread pool size which will be used to allocate back-
ground jobs. If set to 0 then V8 will choose an appropriate size
of the thread pool based on the number of online processors. If
the value provided is larger than V8's maximum, then the largest
value will be chosen.

--zero-fill-buffers
Automatically zero-fills all newly allocated Buffer and Slow-
Buffer instances.

-c, --check
Check the script's syntax without executing it. Exits with an
error code if script is invalid.

-e, --eval string
Evaluate string as JavaScript.

-h, --help
Print command-line options. The output of this option is less
detailed than this document.

-i, --interactive
Open the REPL even if stdin does not appear to be a terminal.

-p, --print string
Identical to -e, but prints the result.

-r, --require module
Preload the specified module at startup. Follows `require()`'s
module resolution rules. module may be either a path to a file,
or a Node.js module name.

-v, --version
Print node's version.

ENVIRONMENT
NODE_DEBUG modules...
Comma-separated list of core modules that should print debug
information.

NODE_DEBUG_NATIVE modules...
Comma-separated list of C++ core modules that should print debug
information.

NODE_DISABLE_COLORS
When set to 1, colors will not be used in the REPL.

NODE_EXTRA_CA_CERTS file
When set, the well-known ``root'' CAs (like VeriSign) will be
extended with the extra certificates in file. The file should
consist of one or more trusted certificates in PEM format.

If file is missing or misformatted, a message will be emitted
once using process.emitWarning(), but any errors are otherwise
ignored.

This environment variable is ignored when `node` runs as setuid
root or has Linux file capabilities set.

NODE_ICU_DATA file
Data path for ICU (Intl object) data. Will extend linked-in data
when compiled with small-icu support.

NODE_NO_WARNINGS
When set to 1, process warnings are silenced.

NODE_OPTIONS options...
A space-separated list of command-line options, which are inter-
preted as if they had been specified on the command-line before
the actual command (so they can be overridden). Node.js will
exit with an error if an option that is not allowed in the envi-
ronment is used, such as --print or a script file.

NODE_PATH directories...
A colon-separated list of directories prefixed to the module
search path.

NODE_PENDING_DEPRECATION
When set to 1, emit pending deprecation warnings.

NODE_PRESERVE_SYMLINKS
When set to 1, the module loader preserves symbolic links when
resolving and caching modules.

NODE_REDIRECT_WARNINGS file
Write process warnings to the given file instead of printing to
stderr. Equivalent to passing --redirect-warnings file on com-
mand-line.

NODE_REPL_HISTORY file
Path to the file used to store persistent REPL history. The
default path is ~/.node_repl_history, which is overridden by this
variable. Setting the value to an empty string ("" or " ") will
disable persistent REPL history.

NODE_TLS_REJECT_UNAUTHORIZED
When set to 0, TLS certificate validation is disabled.

NODE_V8_COVERAGE dir
When set, Node.js writes JavaScript code coverage information to
dir.

OPENSSL_CONF file
Load an OpenSSL configuration file on startup. Among other uses,
this can be used to enable FIPS-compliant crypto if Node.js is
built with ./configure --openssl-fips.

If the --openssl-config command-line option is used, this envi-
ronment variable is ignored.

SSL_CERT_DIR dir
If --use-openssl-ca is enabled, this overrides and sets OpenSSL's
directory containing trusted certificates.

SSL_CERT_FILE file
If --use-openssl-ca is enabled, this overrides and sets OpenSSL's
file containing trusted certificates.

UV_THREADPOOL_SIZE size
Sets the number of threads used in libuv's threadpool to size.

BUGS
Bugs are tracked in GitHub Issues: https://github.com/nodejs/node/issues

COPYRIGHT
Copyright Node.js contributors. Node.js is available under the MIT
license.

Node.js also includes external libraries that are available under a vari-
ety of licenses. See https://github.com/nodejs/node/blob/master/LICENSE
for the full license text.

SEE ALSO
Website: https://nodejs.org/

Documentation: https://nodejs.org/api/

GitHub repository & Issue Tracker: https://github.com/nodejs/node

IRC (general questions): chat.freenode.net #node.js (unofficial)

IRC (Node.js core development): chat.freenode.net #node-dev

AUTHORS
Written and maintained by 1000+ contributors:
https://github.com/nodejs/node/blob/master/AUTHORS

April 4, 2019

 

 

Goのサンプルプログラム

 プログラムの中身としては、

TCPポート7778で待ち受けて、Webクライアントからのアクセスに対して「node.js sample program」という文字列を返すシンプルなものです。

https://github.com/kujiraitakahiro/nginx_unit/blob/master/sample_node.js

bash-3.2$ cat sample_node.js
var http = require('http');
//nginx unitでは require('http') を require('unit-http') に変更する

var server = http.createServer(function (req, res) {
  res.writeHead(200, {"Content-Type": "text/plain"});
  res.end('node.js sample program\n');
});

server.listen(7778);

 

 

 Webクライアントからのアクセス

 Node.jsの実行

bash-3.2$ node sample_node.js

 

ブラウザから「localhost:7778」でアクセスすると、

以下のように作成したコンテンツが返されました。

f:id:opensourcetech:20190405011005p:plain

 

その他、Node.jsでやりたいこと

nginx unitを使って、Goアプリケーションの実行をする予定です。

https://unit.nginx.org/configuration/#go-node-js-applications

 

以下の2点さえ押さえておけばOKとのこと。

・npmを使って、unit-httpをインストールする

・require('http')の代わりに、require('unit-http')を使用する

f:id:opensourcetech:20190405011243p:plain

 

 

 

 

 

www.slideshare.net

github.com

www.facebook.com

twitter.com

www.instagram.com

 

 

にほんブログ村 IT技術ブログ Linuxへ
Linux

にほんブログ村 IT技術ブログ オープンソースへ
オープンソース

 

 

Opensourcetech by Takahiro Kujirai