LoginSignup
1
1

More than 3 years have passed since last update.

Node.js (2)データ処理とモジュール化

Last updated at Posted at 2019-11-07

node.jsのデータ 処理はchrome中にconsoleの機能似てる。

データ処理

先ずはconsole.logに文字列入れる。

app.js
console.log('Hello World');

以下はnodeの実行結果。

terminal
$ node app.js
Hello World

つぎは簡単な変数計算を試しよう。

app.js
var a = 100;
var b = 200;
var c = a+b;
console.log(c);
terminal
$ node app.js
300

モジュール化

複数ファイル間のデータ輸出と輸入につて一般的な方法は三つがある。先ずは二つファイルを作る、app.jsの方はデータ受ける用、data.jsはデータ輸出用。app.js中身のrequire関数は輸出ファイルのバス引数にようるとデータを受け取れる、data.jsはexports函数形、exports変数形とmodule形をまとめる。

app.js
var content = require('./data');
console.log(content.apple());
data.js
//exports函数形
exports.apple = function(){
    return 'apple!!';
}
terminal
$ node app.js
apple!!

次はexports変数形、変数見たいdataで保存する輸出形だ。

app.js
var content = require('./data');
console.log(content.data);
data.js
//exports変数形
exports.data = 100;

terminal
$ node app.js
100

最後はmodule形を試しってmodule.exports中身に保存するデータ輸出形だ。

app.js
var content = require('./data');
console.log(content);
data.js
//module形
module.exports ={
    price:3000
}

terminal
$ node app.js
3000

注意点

同時に使えない!!
```app.js
var content = require('./data');

console.log(content);
console.log(content.data);
console.log(content.apple());
```

data.js
//module形
exports.data = 100;

exports.apple = function(){
    return 'apple!!';
}
module.exports ={
    price:3000
}

terminal
$ node app.js
{ price: 3000 }
undefined
console.log(content.apple());
                    ^

TypeError: content.apple is not a function
    at Object.<anonymous> 
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
1
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
1
1