1. 程式人生 > >nodejs漸入佳境[3]-require匯入模組

nodejs漸入佳境[3]-require匯入模組

require 匯入其他檔案

require可以執行其他檔案的內容。

新建檔案: nodes.js:

1
console.log('start nodes.js');

app.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//列印字串
console.log('Start app.');

const nodes = require('./nodes.js')
//匯入node自帶modules,fs檔案操作
const fs = require('fs');
//os系統操作
const os = require('os'
);

//獲取系統名字
var user = os.userInfo();

//新增字串到回撥函式中,並執行回撥函式。出錯就會報錯,不出錯就會打印出'The "data to append" was appended to file!'
fs.appendFile('greetings.txt',`Hello ${user.username}`,(err) => {
 if (err) throw err;
 console.log('The "data to append" was appended to file!');
}
);

開啟控制檯,在當前目錄下輸入:

1

> node app.js

輸出字串

1
2
3
Start app.
start nodes.js
The "data to append" was appended to file!

require 匯入屬性

nodes.js:

1
2
3
console.log('start nodes.js');

module.exports.age = 25;

app.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//列印字串
console
.log('Start app.');


const nodes = require('./nodes.js')
//匯入node自帶modules,fs檔案操作
const fs = require('fs');
//os系統操作
const os = require('os');
//獲取系統名字
var user = os.userInfo();

//新增字串到回撥函式中,並執行回撥函式。出錯就會報錯,不出錯就會打印出'The "data to append" was appended to file!'
fs.appendFile('greetings.txt',`Hello ${user.username} age ${nodes.age}`,(err) => {
 if (err) throw err;
 console.log('The "data to append" was appended to file!');
}
);

開啟控制檯,在當前目錄下輸入:

1
> node app.js

檔案中儲存:Hello jackson age 25

require 匯入函式

nodes.js:

1
2
3
4
5
6
console.log('start nodes.js');

module.exports.addNote = ()=>{
 console.log('addNode');
 return 'New Node';
};

app.js:

1
2
3
4
5
6
console.log('Start app.');

const nodes = require('./nodes.js')

const res = nodes.addNote();
console.log(res);

開啟控制檯,在當前目錄下輸入:

1
> node app.js

輸出字串

1
2
3
4
Start app.
start nodes.js
addNode
New Node

require 匯入帶參函式

nodes.js:

1
2
3
4
5
6
7
8
9
10
11
console.log('start nodes.js');

module.exports.add = (a,b)=>{

 return a+b;
};

module.exports.addNote = ()=>{
 console.log('addNode');
 return 'New Node';
};

app.js:

1
2
3
4
5
6
7
//列印字串
console.log('Start app.');

const nodes = require('./nodes.js')

const res = nodes.add(1,2);
console.log(res);

開啟控制檯,在當前目錄下輸入:

1
> node app.js

輸出字串

1
2
3
Start app.
start nodes.js
3

image.png