Node.js 模塊簡單用法

之前使用node的包管理器npm,生成vue-cli工程模板,而且經常通過npm進行包管理,爲了更好的瞭解nodejs包管理,學習一下nodejs
一、使用Nodejs搭建一個web服務器

默認大家已經安裝好了node,直接寫項目

1.1、創建文件夾 scott > imooc > begining
         創建文件 server.js

var http = require('http')

var server = http.createServer(function (req, res) {
    res.writeHead(200,{'Content-Type':'text/plain'})
    res.end('Hello Nodejs \n')
})
server.listen(1337, '127.0.0.1')

1.2、運行文件

//cmd cd 當前目錄中
scott\imooc\begining> node server   

1.3、打開瀏覽器輸入 127.0.0.1:1337
         頁面顯示 Hello Nodejs

二、簡單的node模塊

創建模塊、導出模塊、加載模塊、使用模塊

2.1、創建模塊 school > student.js

// 編寫方法
function add (stu) {
    console.log('New student:' + stu)
}
// 導出模塊
exports.add = add

2.2、創建文件 school > stuInfo.js

// 加載模塊
var stu = require('./stu')

// 使用模塊
stu.add('小明')

2.3、運行文件,運行方法,顯示信息

// cmd  當前路徑,執行命令
school>node stuInfo
New student:小明
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章