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:小明