LoginSignup
3
1

More than 3 years have passed since last update.

Node.jsを勉強する③ - Javascriptファイル間の連携

Posted at

はじめに

前回はテキストファイルの作成についてまとめました。
今回はJavascriptファイル間の連携について記事にします。

教材

Udemy
The Complete Node.js Developer Course (3rd Edition)
https://www.udemy.com/course/the-complete-nodejs-developer-course-2/

ファイルの作成

連携したいJavascrptのファイルを2つ作ります。
それぞれ、app.jsとutils.jsと名付け、utils.jsにconsol.logを用いてメッセージを書きます。

utils.js
console.log("The JS files are connected!")

ファイルの連携

今回は、utils.jsをapp.js上で呼び出します。
requireを用いますが、その際、呼び出したいファイル(今回はutils.js)までの相対パスで書きます。

app.js
require('./utils.js')

今回は、utils.jsとapp.jsを同じ階層に配置したので、"."を用いて階層をひとつ戻ってから、utils.jsと書きました。
ターミナルでnode app.jsを実行すると、"The JS files are connected!"と表示されます

ターミナル
node app.js
The JS files are connected!

他ファイルのオブジェクトを使う

今度は、他のファイルの中で定義されたオブジェクトを使います。
まずは、呼び出したい先のファイルに
module.exports = 取り出したいオブジェクト名 と書くことで、ファイル全体をエクスポートします。

utils.js
const name = "Tom"
module.exports = name 

app.jsで呼び出し、console.logを用いて、出力してみます。
utils.jsはオブジェクトになっているので、変数を定義してapp.js上でも使えるようにします。

app.js
const utils= require('./utils.js')
console.log(utils)

ターミナルで、app.jsを実行すると、utils.jsの変数nameの中身が取り出せます。

ターミナル
node app.js
Tom

複数のオブジェクトを取り出す場合

ひとつのjsファイルから複数のオブジェクトを取り出す場合は、配列にします。

app.js
const name = "Taro"
const address = "Tokyo"

module.exports = {
    name: name,
    address: address
}

取り出すときは、配列名を定義して、配列名.要素名で取り出します。

app.js
const utilsVariables = require('./utils.js')

console.log("My name is " + utilsVariables.name)
console.log("I live in "+utilsVariables.address)

実行結果は以下の通りです。

ターミナル
node app.js
My name is Taro
I live in Tokyo
3
1
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
3
1