LoginSignup
5
5

More than 3 years have passed since last update.

WSL環境におけるNode.jsの導入から利用

Last updated at Posted at 2020-04-21

はじめに

投稿者の備忘録としての活用が主です。
Webの作成において役に立つNode.jsを導入します。

環境

wsl(Windows Subsystem for Linux)にインストールします。

Editor: VSCode
Shell: bash version 4.4.20
Ubuntu: 18.04.4 LTS

目次

  1. nvmの導入 >>
  2. Node.jsの導入 >>
  3. REPLを使ってみる >>
  4. ファイルを実行してみる >>

1.nvmの導入

Node.jsのバージョンを管理するためにまずnvmを導入します。
現在利用しているNode.jsのバージョンの把握
別バージョンへの切り替えなどを行えます。

wsl
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

終了したら、

wsl
$ source ~/.bashrc 

で、.bashrcの内容を読み込んでおきます。

wsl
$ nvm

Node Version Manager

Note: <version> refers to any version-like string nvm understands. This includes:
  - full or partial version numbers, starting with an optional "v" (0.10, v0.1.2, v1)
  - default (built-in) aliases: node, stable, unstable, iojs, system
  - custom aliases you define with `nvm alias foo`
以下略。。。

となれば、インストールが成功しています。

2.Node.jsの導入

今回、Ver. 10.14.2 のNode.jsをインストールしました。

wsl
$ nvm install v10.14.2
Downloading and installing node v10.14.2...
Downloading https://nodejs.org/dist/v10.14.2/node-v10.14.2-linux-x64.tar.xz...
###################################################################### 100.0%Computing checksum with sha256sum
Checksums matched!
Now using node v10.14.2 (npm v6.4.1)
Creating default alias: default -> v10.14.2
$ nvm use v10.14.2
Now using node v10.14.2 (npm v6.4.1)
$ node --version
v10.14.2

指定したバージョンのNode.jsがインストールされていることを確認しました。

3.REPLを使ってみる

Node.js版のコンソールだと思えばいいと思います。
(PythonのPythonコンソール的な感じ)
Ctrl+c二回でREPLを終了できます。

REPL
$ node
> 1+1
2
>
(To exit, press ^C again or type .exit)
> 

4.ファイルを実行してみる

プログラムの書き方は、JavaScriptと同じかきかたをすればいいと思います。
今回単純な足し算プログラムを書いて動かします。

ソースコード

sum.js
'use strict';
function aAdd(num) {
    var res = 0;
    num[0] = 0;
    num[1] = 0;
    for (let s of num) {
        res += parseInt(s);
    }
    console.log(res);
}
aAdd(process.argv);

実行結果

wsl
$ node sum.js 1 2 3 4
10
$ node sum.js      
0

雑に解説

これは、引数の総和をとるプログラムでした。
process.argvに命令がリストとして入っています。
$ node sum.js 1 1 1 2 3を実行したとすると、
リストの中身は、

[ '/home/yosse95ai/.nvm/versions/node/v10.14.2/bin/node',
  '/home/yosse95ai/sum.js',
  '1',
  '1',
  '1',
  '2',
  '3' ]

といった具合になっています。

だから、

num[0] = 0;
num[1] = 0;

の部分で数字以外の文字列部分(パス部分)を、0に置き換えてます。
多分もっとクレバーなやり方があると思います。

おわりに

今回は、かなり初歩的な解説でした。
まだ自分が初心者なので、頭の整理を兼ねて書きました。
おそらく拙い文章でしたが、お付き合いいただきありがとうございました。
さよなら:wave:

関連記事

参考

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5