1. 程式人生 > >node筆記

node筆記

version 技術分享 inpu brush func 用戶 交互 text head

此筆記由菜鳥教程提供

0.

下載地址:https://nodejs.org/en/download/

node -v / node -- version  查看版本

node            進入node模式(在cmd中運行,REPL(Read Eval Print Loop:交互式解釋器) ctrl + c退出

第一個服務器

const http = require("http");

http.createServer(function (request,response) {

    // 服務器對訪問瀏覽器的響應頭
    response.writeHead(200, {‘Content-Type‘: ‘text/plain‘});

    // 服務器對訪問瀏覽器的響應數據
    response.end(‘Hi World\n‘);
}).listen(8888);

console.log(‘Server running at http://127.0.0.1:8888/‘);  //在瀏覽器訪問127.0.0.1:8888

  

1.模塊

①.node自帶:

(1)http(開啟服務): http.createServer() 方法創建服務器; request, response 參數來接收和響應數據

(2)fs(文件系統): 像操作window的文件和文件夾,執行增刪改查

②.node需引入

2.npm

NPM是隨同NodeJS一起安裝的包管理工具,常見的使用場景有以下幾種:

允許用戶從NPM服務器下載別人編寫的第三方包到本地使用。

允許用戶從NPM服務器下載並安裝別人編寫的命令行程序到本地使用。

允許用戶將自己編寫的包或命令行程序上傳到NPM服務器供別人使用。

①.npm -v    npm 版本

②.安裝

npm install 模塊名      本地安裝模塊

npm install 模塊名 -g    全局安裝模塊

express@4.13.3 node_modules/express

③.查看

npm list -g        所有全局安裝的模塊

④.卸載

npm unstall 模塊名    卸載模塊

npm ls          是否卸載

⑤.更新

npm update 模塊名    更新模塊

⑥.探索

npm search 模塊名    探索有模塊名(模糊查詢)

⑦.分布

npm publish       分布模塊

更多詳情>>

3.回調函數

4.事件循環

技術分享圖片

執行異步操作的函數將回調函數作為最後一個參數回調函數接收錯誤對象作為第一個參數

var fs = require("fs");

fs.readFile(‘input.txt‘, function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});
console.log("程序執行完畢");
//不存在input.txt就報錯

  

  

cmd模式node不能運行node.js文件不然報錯

技術分享圖片

node筆記