Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9082

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

$
0
0

はじめに

前回はテキストファイルの作成についてまとめました。
今回は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
constname="Tom"module.exports=name

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

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

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

ターミナル
node app.js
Tom

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

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

app.js
constname="Taro"constaddress="Tokyo"module.exports={name:name,address:address}

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

app.js
constutilsVariables=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

Viewing all articles
Browse latest Browse all 9082

Latest Images

Trending Articles