溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

nodejs漸入佳境[3]-require導(dǎo)入模塊

發(fā)布時(shí)間:2020-08-05 15:21:17 來源:網(wǎng)絡(luò) 閱讀:563 作者:jonson_jackson 欄目:開發(fā)技術(shù)

require 導(dǎo)入其他文件

require可以執(zhí)行其他文件的內(nèi)容。

新建文件: 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')
//導(dǎo)入node自帶modules,fs文件操作
const fs = require('fs');
//os系統(tǒng)操作
const os = require('os');
//獲取系統(tǒng)名字
var user = os.userInfo();

//添加字符串到回調(diào)函數(shù)中,并執(zhí)行回調(diào)函數(shù)。出錯(cuò)就會(huì)報(bào)錯(cuò),不出錯(cuò)就會(huì)打印出'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!');
}
);

打開控制臺(tái),在當(dāng)前目錄下輸入:

1
> node app.js

輸出字符串

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

require 導(dǎo)入屬性

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')
//導(dǎo)入node自帶modules,fs文件操作
const fs = require('fs');
//os系統(tǒng)操作
const os = require('os');
//獲取系統(tǒng)名字
var user = os.userInfo();

//添加字符串到回調(diào)函數(shù)中,并執(zhí)行回調(diào)函數(shù)。出錯(cuò)就會(huì)報(bào)錯(cuò),不出錯(cuò)就會(huì)打印出'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!');
}
);

打開控制臺(tái),在當(dāng)前目錄下輸入:

1
> node app.js

文件中存儲(chǔ):Hello jackson age 25

require 導(dǎo)入函數(shù)

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);

打開控制臺(tái),在當(dāng)前目錄下輸入:

1
> node app.js

輸出字符串

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

require 導(dǎo)入帶參函數(shù)

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);

打開控制臺(tái),在當(dāng)前目錄下輸入:

1
> node app.js

輸出字符串

1
2
3
Start app.
start nodes.js
3
  • 本文鏈接: https://dreamerjonson.com/2018/11/13/node-3-require/

  • 版權(quán)聲明: 本博客所有文章除特別聲明外,均采用 CC BY 4.0 CN協(xié)議 許可協(xié)議。轉(zhuǎn)載請注明出處!

nodejs漸入佳境[3]-require導(dǎo)入模塊

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI