15
13

More than 5 years have passed since last update.

Node.js 実践講座 〜基礎編〜 その6

Last updated at Posted at 2015-12-16

はじめに

この記事では、Node.jsのmoduleexportsを使用して、ソースコードを複数のファイルに分割して記述する方法を学びます。

ワークスペースの作成

下記コマンドを入力してワークスペースを作成します。

mkdir ~/workspace/js/basic/03-module

mkdir ~/workspace/js/basic/03-module/01-module-exports
touch ~/workspace/js/basic/03-module/01-module-exports/index.js
touch ~/workspace/js/basic/03-module/01-module-exports/print.js

mkdir ~/workspace/js/basic/03-module/02-exports
touch ~/workspace/js/basic/03-module/02-exports/index.js
touch ~/workspace/js/basic/03-module/02-exports/math.js

module.exports

ソースコードの内容

01-module-exportsindex.jsprint.jsの内容を下記に示します。

index.js
'use strict';

var print = require('./print')

if (require.main === module) {
  main()
}

function main() {
  print('Hello, world.')
}
math.js
'use strict';

module.exports = print

function print(str) {
  console.log(str)
}

実行コマンド

実行コマンドを下記に示します。

node index

実行結果

実行結果を下記に示します。

Hello, world.

解説

読み込まれる側のファイルではmodule.exportsへの代入により、関数や変数をエクスポートすることができます。一方、読み込む側のファイルではrequireで相対パスを呼び出し、関数や変数をインポートすることができます。

exports

ソースコードの内容

02-module-exportsindex.jsmath.jsの内容を下記に示します。

math.js
'use strict';

exports.add = add
exports.sub = sub
exports.mul = mul
exports.div = div

function add(left, right) {
  return left + right
}

function sub(left, right) {
  return left - right
}

function mul(left, right) {
  return left * right
}

function div(left, right) {
  return left / right
}

index.js
'use strict';

var math = require('./math')

if (require.main === module) {
  main()
}

function main() {
  console.log('1 + 2 = ' + math.add(1, 2))
  console.log('3 - 4 = ' + math.sub(4, 3))
  console.log('5 * 6 = ' + math.mul(5, 6))
  console.log('7 / 8 = ' + math.div(10, 3))
}

実行コマンド

実行コマンドを下記に示します。

node index

実行結果

実行結果を下記に示します。

1 + 2 = 3
3 - 4 = 1
5 * 6 = 30
7 / 8 = 3.3333333333333335

解説

読み込まれる側のファイルではexportsの任意のプロパティへの代入により、関数や変数をエクスポートすることができます。一方、読み込む側のファイルではmoduleの場合と同様にrequireで相対パスを呼び出し、関数や変数をインポートすることができます。なお、modoule.exports.xxxなどに代入することによってexportsを使用した場合と同じ効果を得ることができます。

おわりに

次回はnpmを使用してパッケージをインストールし、インストールしたパッケージを使用する方法について解説します。

15
13
1

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
15
13