Node.js筆記
- Node.js
- Node.js安裝
- 快速入門
-
- 建立測試工程
- 使用函數
- 使用子產品
- 建立http服務
- 服務端渲染
- 接收參數
- 資料總管NPM
-
- 工程建立
- 本地安裝
- 全局安裝
- 修改鏡像
- Webpack快速入門
-
- 安裝webpack
- 快速入門
- css打包
Node.js
簡單的說 Node.js 就是運作在服務端的 JavaScript。
Node.js 是一個基于Chrome JavaScript 運作時建立的一個平台。
Node.js是一個事件驅動I/O服務端JavaScript環境,基于Google的V8引擎,V8引擎執行Javascript的速度非常快,性能非常好。
Node.js安裝
1、下載下傳對應你系統的Node.js版本:
https://nodejs.org/en/download/ 資料 檔案夾中已經提供。
2、選安裝目錄進行安裝
完成以後,在控制台輸入:
C:\Users\jack>node -v
v10.17.0
快速入門
建立測試工程
建立一個工程demo1,使用開發工具打開,這裡使用的是WebStorm2020.1版本;
建立一個node01.js檔案,在裡面輸入:
使用函數
使用子產品
每個檔案就是一個子產品,有自己的作用域。在一個檔案裡面定義的變量、函數、類,都是私有的,對其他檔案不可
見。每個子產品内部,module變量代表目前子產品。這個變量是一個對象,它的exports屬性(即module.exports)
是對外的接口。加載某個子產品,其實是加載該子產品的module.exports屬性。
建立node03.1.js
exports.add = function (a, b) {
return a + b;
}
建立node03.2.js
var demo = require('./node03.1');
console.log(demo.add(10, 20));
指令行執行
D:\autobackup\備課教案\node\code\demo1>node node03.2.js
30
建立http服務
http為node内置的web子產品。建立node04.js檔案
/*http server*/
const http = require('http')
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('hello world');
res.end('\n');
}).listen(8000)
console.log("伺服器監聽8000端口")
執行:
node node04.js
浏覽器通路位址:http://localhost:8000
服務端渲染
建立node05.js
/*http server*/
const http = require('http')
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/html'
});
for (var i = 0; i < 5; i++) {
res.write('<h1>hello world</h1>');
}
res.end('\n');
}).listen(8000)
console.log("伺服器監聽8000端口")
通過浏覽器通路
接收參數
建立檔案node06.js
/*http server*/
const http = require('http')
const url = require('url')
http.createServer((req, res) => {
// 解析url位址中的查詢字元串,true将解析後的參數轉成對象
var params = url.parse(req.url, true).query;
res.writeHead(200, {
'Content-Type': 'text/html'
});
for (var key in params) {
res.write(`<h1>${key}:${params[key]}</h1>`);
}
res.end('\n');
}).listen(8000)
console.log("伺服器監聽8000端口")
通過url通路:http://localhost:8000/?username=jack&age=20
通路結果:
資料總管NPM
npm全稱Node Package Manager,是node包管理和分發工具。其實我們可以把NPM了解為前端的Maven 。
通過npm 可以很友善地下載下傳js庫,管理前端工程。
現在的node.js已經內建了npm工具,在指令提示符輸入 npm -v 可檢視目前npm版本
工程建立
建立一個空的檔案夾 demo2,使用WebStorm打開,在終端執行
npm init
D:\autobackup\備課教案\node\code\demo2>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (demo2)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\autobackup\備課教案\node\code\demo2\package.json:
{
"name": "demo2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
D:\autobackup\備課教案\node\code\demo2>
index.js
是入口檔案,相當于
java
中的
main
函數,可以指定,預設是
index.js
按照提示輸入相關資訊,如果是用預設值則直接回車即可。
name: 項目名稱
version: 項目版本号
description: 項目描述
keywords: {Array}關鍵詞,便于使用者搜尋到我們的項目
最後會生成 package.json 檔案,這個是包的配置檔案,相當于maven的pom.xml
之後也可以根據需要進行修改。
本地安裝
全局安裝
全局安裝
npm install express -g
預設的全局安裝路徑
{sys.user}/node_modules
修改鏡像
D:\autobackup\備課教案\node\code\demo2>npm install -g nrm
npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to u
se Promises in 1.x.)
npm WARN deprecated [email protected]: CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
C:\Users\jack\AppData\Roaming\npm\nrm -> C:\Users\jack\AppData\Roaming\npm\node_modules\nrm\cli.js
+ [email protected]
added 494 packages from 880 contributors in 22.259s
D:\autobackup\備課教案\node\code\demo2>nrm ls
npm -------- https://registry.npmjs.org/
yarn ------- https://registry.yarnpkg.com/
cnpm ------- http://r.cnpmjs.org/
taobao ----- https://registry.npm.taobao.org/
nj --------- https://registry.nodejitsu.com/
npmMirror -- https://skimdb.npmjs.com/registry/
edunpm ----- http://registry.enpmjs.org/
D:\autobackup\備課教案\node\code\demo2>nrm use taobao
Registry has been set to: https://registry.npm.taobao.org/
D:\autobackup\備課教案\node\code\demo2>
Webpack快速入門
Webpack 是一個前端資源加載/打包工具。它将根據子產品的依賴關系進行靜态分析,然後将這些子產品按照指定的規則生成對應的靜态資源。webpackjs
安裝webpack
npm install webpack -g
npm install webpack-cli -g
webpack -v
快速入門
工程結構
建立
src
檔案夾,在src下建立
bar.js
export default function bar(str) {
document.write(str);
}
在
src
下建立
done.js
export default function add(a, b) {
return a + b;
}
在
index.js
編寫如下代碼
import bar from "./src/bar";
import add from "./src/done";
bar('10+20=' + add(10, 20))
建立
webpack.config.js
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
執行
webpack
指令進行打包後生成
dist
檔案夾,生成檔案
bundle.js
建立
index.html
引用
bundle.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<script src="./dist/bundle.js"></script>
</head>
<body>
</body>
</html>
css打包
安裝style-loader和 css-loader
Webpack 本身隻能處理 JavaScript 子產品,如果要處理其他類型的檔案,就需要使用 loader 進行轉換。 Loader可以了解為是子產品和資源的轉換器,它本身是一個函數,接受源檔案作為參數,傳回轉換的結果。這樣,我們就可以通過 require來加載任何類型的子產品或檔案,比如 CoffeeScript、 JSX、 LESS 或圖檔。首先我們需要安裝相關Loader插件,css-loader 是将 css 裝載到 javascript;style-loader 是讓 javascript 認識css
npm install style-loader css-loader --save-dev
–save-dev : 不會在打包的時候打包。
編寫
css
修改
index.js
重新打包
webpack
後通路頁面