Node-01
會 JavaScript,就能學會 Node.js!!!
**Node.js 的官網地址:
**
Node.js 的學習路徑:
JavaScript 基礎語法 + Node.js 內置 API 模塊(fs、path、http等)+ 第三方 API 模塊(express、mysql 等)
查看已安裝的 Node.js 的版本號
打開終端,在終端輸入命令 node –v 后,按下回車鍵,即可查看已安裝的 Node.js 的版本號。
使用Node執行JS代碼
REPL模式(了解)
node
> 這里寫你的JS代碼
Ctrl+C
Ctrl+C
這個模式,只適合,執行一些簡單的JS代碼
終端使用node命令執行js文件(推薦)
- vscode打開代碼文件夾
- 在文件上右鍵–> 在終端中打開
- 好處是,終端中執行node命令的文件夾,已經定位好了,我們不用切換文件夾了
- 終端中,
node js文件
,回車
Node內置模塊
fs 文件系統模塊
內置模塊,就相當于瀏覽器中的內置對象一樣。都是對象,每個對象里面有很多方法和屬性。
什么是 fs 文件系統模塊
fs 模塊是 Node.js 官方提供的、用來操作文件的模塊。它提供了一系列的方法和屬性,用來滿足用戶對文件的操作需求。
例如:
? fs.readFile() 方法,用來讀取指定文件中的內容
? fs.writeFile() 方法,用來向指定的文件中寫入內容
- fs – file system 文件系統
- 讀取文件夾
- 讀取文件
- 創建文件
- 寫入文件
- …
- path
- querystring
- http
- …
如何使用內置模塊
- 加載模塊
const fs = require('fs')
;
- 調用模塊的方法
fs模塊(file system 文件系統)
-
fs.readFile() – 異步讀取文件
fs.readFile(文件名, 'utf-8', (err, data) => {if (err) return console.log(err);data 就是讀取的結果 });
-
fs.writeFile() – 異步寫入文件
fs.writeFile(文件名, 內容, (err) => {});
- fs.readdir() – 異步讀取文件夾(了解)
path模塊
- path.join(__dirname, ‘文件名’);
- __dirname 是node內置的全局變量
// path -- 路徑 const path = require('path');// path.join(路徑1,路徑2,路徑3...); // 方法會把給出的路徑拼接到一起// console.log( path.join('a', 'b', 'c') ); // a/b/c
// console.log( path.join('a', '/b/', 'c') ); // a/b/c
// console.log( path.join('a', '/b/', 'c', 'index.html') ); // a/b/c/index.html
// console.log( path.join('a', 'b', '../c', 'index.html') ); // a/c/index.html
// console.log(__dirname); // node自帶的全局變量,表示當前js文件所在的絕對路徑// 拼接成績.txt的絕對路徑
console.log( path.join(__dirname, '成績.txt') ); // ------ 最常用的
__dirname 表示當前js文件所在的路徑(絕對路徑)
path.extname() – 找文件的后綴;了解 path.basename() – 找文件的文件名;了解
const path = require('path');// 找字符串中,最后一個點及之后的字符
// console.log( path.extname('index.html') ); // .html
// console.log( path.extname('a.b.c.d.html') ); // .html
// console.log( path.extname('asdfas/asdfa/a.b.c.d.html') ); // .html
// console.log( path.extname('adf.adsf') ); // .adsf// 找文件名
// console.log( path.basename('index.html') ); // index.html
// console.log( path.basename('a/b/c/index.html') ); // index.html
// console.log( path.basename('a/b/c/index.html?id=3') ); // index.html?id=3
console.log( path.basename('/api/getbooks') ); // getbooks
querystring模塊
- querystring.parse() – 把查詢字符串轉成對象
- querystring.stringify() – 把對象轉成查詢字符串
const querystring = require('querystring');// querystring -- 查詢字符串
/*** 什么是查詢字符串* 發送請求的時候,攜帶的字符串參數* booksname=xxx&author=xxx*/let str = 'id=3&bookname=xiyouji&author=tangseng';// 一:把查詢字符串轉成對象let obj = querystring.parse(str);
// console.log(obj); // {id: '3', bookname: 'xiyouji', author: 'tangseng'}// 二:把對象轉成查詢字符串console.log( querystring.stringify(obj) ); // id=3&bookname=xiyouji&author=tangseng