node.js入門學習筆記整理

(1)node

Node.js 是一個基於 Chrome V8 引擎的 JavaScript 運行環境。
Node與javaScript的區別在於,javaScript的頂層對象是window,而node是globalcss

//這裏使用的var聲明的變量不是全局的,是當前模塊下的,用global聲明的表示是全局的
var s = 100;
global.s = 200;
//這裏訪問到的s是var生命的
console.log(s); //100
//這裏訪問到的纔是全局變量
console.log(global.s); //200

模塊:在node中,文件和模塊是一一對應的,也就是一個文件就是一個模塊;每一個模塊都有本身的做用域,咱們經過var申明的變量並不是全局而是該模塊做用域下的。html

(2)module模塊

一、文件查找

1)首先按照加載的模塊的文件名稱進行查找,若是沒有找到,則會帶上 .js、.json 或 .node 拓展名在加載
2)以 '/' 爲前綴的模塊是文件的絕對路徑。 例如,require('/home/marco/foo.js') 會加載 /home/marco/foo.js 文件。
3)以 './' 爲前綴的模塊是相對於調用 require() 的文件的。 也就是說,circle.js 必須和 foo.js 在同一目錄下以便於 require('./circle') 找到它。
4)當沒有以 '/'、'./' 或 '../' 開頭來表示文件時,這個模塊必須是一個核心模塊或加載自 node_modules 目錄。
5)若是給定的路徑不存在,則 require() 會拋出一個 code 屬性爲 'MODULE_NOT_FOUND' 的 Error。前端

二、module 做用域

在一個模塊中經過var定義的變量,其做用域範圍是當前模塊,外部不可以直接的訪問,若是咱們想一個模塊可以訪問另一個模塊中定義的變量,能夠有一下兩種方式:
1)把變量做爲global對象的一個屬性,但這樣的作法是不推薦的
2)使用模塊對象 module。module保存提供和當前模塊有關的一些信息。
在這個module對象中有一個子對象exports對象,咱們能夠經過這個對象把一個模塊中的局部變量對象進行提供訪問。java

//這個方法的返回值,其實就是被加載模塊中的module.exports
require('./02.js');

三、__dirname:當前模塊的目錄名。

例子,在 /Users/mjr 目錄下運行 node example.js:
console.log(__dirname);
// 輸出: /Users/mjr
console.log(path.dirname(__filename));
// 輸出: /Users/mjr

四、__filename:當前模塊的文件名(處理後的絕對路徑)。當前模塊的目錄名可使用 __dirname 獲取。

在 /Users/mjr 目錄下運行 node example.js:

console.log(__filename);
// 輸出: /Users/mjr/example.js
console.log(__dirname);
// 輸出: /Users/mjr

(3)process(進程)

process 對象是一個全局變量,提供 Node.js 進程的有關信息以及控制進程。 由於是全局變量,因此無需使用 require()。node

一、process.argv

返回進程啓動時的命令行參數。第一個元素是process.execPath。第二個元素是當前執行的JavaScript文件的路徑。剩餘的元素都是額外的命令行參數。web

console.log(process.argv);

打印結果:
json

二、process.execPath返回啓動進程的可執行文件的絕對路徑。

三、process.env 返回用戶的環境信息。

在process.env中能夠新增屬性:數組

process.env.foo = 'bar';
console.log(process.env.foo);

能夠經過delete刪除屬性:服務器

delete process.env.foo;
console.log(process.env);

在Windows上,環境變量不區分大小寫網絡

四、process.pid 屬性返回進程的PID。

五、process.platform屬性返回字符串,標識Node.js進程運行其上的操做系統平臺。

六、process.title 屬性用於獲取或設置當前進程在 ps 命令中顯示的進程名字

七、process.uptime() 方法返回當前 Node.js 進程運行時間秒長

注意: 該返回值包含秒的分數。 使用 Math.floor() 來獲得整秒鐘。

八、process.versions屬性返回一個對象,此對象列出了Node.js和其依賴的版本信息。

process.versions.modules代表了當前ABI版本,此版本會隨着一個C++API變化而增長。 Node.js會拒絕加載模塊,若是這些模塊使用一個不一樣ABI版本的模塊進行編譯。

九、process對象-輸入輸出流

var a;
var b;
process.stdout.write('請輸入a的值: ');
process.stdin.on('data', (chunk) => {
    if (!a) {
        a = Number(chunk);
        process.stdout.write('請輸入b的值:');
    }else{
        b = Number(chunk);
        process.stdout.write('a+b的值:'+(a+b));
        process.exit();
    }
});

(4)Buffer緩衝器

Buffer類,一個用於更好的操做二進制數據的類,咱們在操做文件或者網絡數據的時候,其實操做的就是二進制數據流,Node爲咱們提供了一個更加方便的去操做這種數據流的類Buffer,他是一個全局的類

一、如何建立使用buffer

Buffer.from(array) 返回一個 Buffer,包含傳入的字節數組的拷貝。
Buffer.from(arrayBuffer[, byteOffset [, length]]) 返回一個 Buffer,與傳入的 ArrayBuffer 共享內存。
Buffer.from(buffer) 返回一個 Buffer,包含傳入的 Buffer 的內容的拷貝。
Buffer.from(string[, encoding]) 返回一個 Buffer,包含傳入的字符串的拷貝。
Buffer.alloc(size[, fill[, encoding]]) 返回一個指定大小且已初始化的 Buffer。 該方法比 Buffer.allocUnsafe(size) 慢,但能確保新建立的 Buffer 不會包含舊數據。
Buffer.allocUnsafe(size) 與 Buffer.allocUnsafeSlow(size) 返回一個指定大小但未初始化的 Buffer。 由於 Buffer 是未初始化的,可能包含舊數據。

// 建立一個長度爲 十、且用 01 填充的 Buffer。
const buf1 = Buffer.alloc(10,1);
// 建立一個長度爲 十、且未初始化的 Buffer。
// 這個方法比調用 Buffer.alloc() 更快,但返回的 Buffer 實例可能包含舊數據,所以須要使用 fill() 或 write() 重寫。
const buf2 = Buffer.allocUnsafe(10);
const buf3 = Buffer.from([1, 2, 3]);
const buf4 = Buffer.from('tést');
console.log(buf1); //<Buffer 01 01 01 01 01 01 01 01 01 01>
console.log(buf2); //<Buffer 00 00 00 00 08 00 00 00 07 00>
console.log(buf3); //<Buffer 01 02 03>
console.log(buf4); //<Buffer 74 c3 a9 73 74>

二、Buffer對象提供的toString、JSON的使用

1)buf.toString(encoding,start,end)

var bf = Buffer.from('miaov');
console.log(bf.toString('utf-8',1,4)); //iaov
console.log(bf.toString('utf-8',0,5)); //miaov
console.log(bf.toString('utf-8',0,6)); //miaov

2)buf.write(string,offset,length,encoding)
string 要寫入 buf 的字符串。
offset 開始寫入的偏移量。默認 0,這裏指的是buffer對象的起始要寫入的位置。
length 要寫入的字節數。默認爲 buf.length - offset。
encoding string 的字符編碼。默認爲 'utf8'。
返回: 已寫入的字節數。

var str = "miaov hello";
var bf = Buffer.from(str);
var bf2 = Buffer.alloc(8);
//從0開始寫入5個
bf2.write(str,0,5);
console.log(bf);
console.log(bf2);

3)buf.toJSON()

const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);

console.log(json);
// 輸出: {"type":"Buffer","data":[1,2,3,4,5]}

三、Buffer中靜態方法的使用

1)Buffer.isEncoding(encoding) : 判斷是不是Buffer支持的字符編碼,是則返回true,不是則返回false

console.log(Buffer.isEncoding('utf-8')); //true

2)Buffer.isBuffer(obj) :若是 obj 是一個 Buffer,則返回 true,不然返回 false。

(5)fs(文件系統)

該模塊是核心模塊,須要使用require('fs')導入後使用,該模塊主要用來操做文件

一、fs.open(path, flags, mode, callback)
path:要打開的文件的路徑;
flags:打開文件的方式 讀/寫;
mode:設置文件的模式 讀/寫/執行
callback(err,fd):文件打開之後,在回調函數中作相應的處理,回調函數的兩個參數:
err:文件打開失敗的錯誤保存在err裏面,若是成功err爲null
fd:被打開文件的標識

var fs = require('fs');
fs.open('./test.txt','r',function(err,fd){
  if(err){
        console.log("文件打開失敗");
    }else{
        console.log("文件打開成功");
    }
});

二、fs.openSync(path, flags, mode) :返回文件描述符。

var fs = require('fs');
console.log(fs.openSync('./test.txt','r')); //3

三、fs.read(fd, buffer, offset, length, position, callback)
從 fd 指定的文件中讀取數據;
buffer 指定要寫入數據的 buffer;
offset 指定 buffer 中開始寫入的偏移量;
length 指定要讀取的字節數;
position 指定文件中開始讀取的偏移量。 若是 position 爲 null,則從文件的當前位置開始讀取;
callback 有三個參數 (err, bytesRead, buffer)

示例:test.txt 中的值爲123456789

fs.open('./test.txt','r',function(err,fd){
    if(!err){
        var bf = Buffer.alloc(5);
        fs.read(fd,bf,0,5,0,function(){
            console.log(bf.toString()); //12345
        })
    }
});

四、fs.write(fd, buffer, offset, length, position, callback)
將 buffer 寫入到 fd 指定的文件。
offset 指定 buffer 中要開始被寫入的偏移量,length 指定要寫入的字節數。
position 指定文件中要開始寫入的偏移量。 若是 typeof position !== 'number',則從當前位置開始寫入。
callback 有三個參數 (err, bytesWritten, buffer),其中 bytesWritten 指定 buffer 中已寫入文件的字節數。

var fs = require('fs');

fs.open('./test.txt','r+',function(err,fd){
    if(!err){
        var bf = Buffer.alloc(5);
        fs.read(fd,bf,0,5,0,function(){
            console.log(bf.toString()); //12345
        });
        var bf = Buffer.from('test數據');
        fs.write(fd,bf,0,10,0);
        fs.write(fd,'測試數據2',10,'utf-8');

    }
});

fs.write(fd, string, position, encoding, callback)
將 string 寫入到 fd 指定的文件。 若是 string 不是一個字符串,則會強制轉換成字符串。
position 指定文件中要開始寫入的偏移量。 若是 typeof position !== 'number',則從當前位置開始寫入。
encoding 指定字符串的編碼。
callback 有三個參數 (err, written, string),其中 written 指定字符串中已寫入文件的字節數。 寫入的字節數與字符串的字符數是不一樣的。

五、fs.exists(path,callback)檢查指定路徑的文件或者目錄是否存在
fs.appendFile(path, data, callback):將數據追加到文件,若是文件不存在則建立文件。

//檢查文件是否存在
var fs = require('fs');
var filename = './test2.txt';
fs.exists(filename,function(isExists){
        if(!isExists){
            fs.writeFile(filename,'miaov',function(err){
                if(err){
                    console.log("文件建立失敗");
                }else{
                    console.log("文件建立成功");
                }
            });
        }else{
            fs.appendFile(filename,'-leo',function(err){
                if(err){
                    console.log("文件內容追加失敗");
                }else{
                    console.log("文件內容追加成功");
                }
            })
        }
});

(6)前端項目自動化構建

一、建立myProject項目文件以及對應的文件夾

var projectData ={
    'name':'myProject',
    'fileData':[
        {
            'name':'css',
            'type':'dir'
        },{
            'name':'js',
            'type':'dir'
        },{
            'name':'images',
            'type':'dir'
        },{
            'name':'index.html',
            'type':'file',
            'content' : '<html>\n\t<head>\n\t\t<title>title</title>\n\t</head>\n\t<body>\n\t\t<h1>Hello</h1>\n\t</body>\n</html>'
        }
    ]
};

var fs = require('fs');

if(projectData.name){
    // 建立項目文件夾
    fs.mkdirSync(projectData.name);
    var fileData = projectData.fileData;
    if(fileData && fileData.length){
        fileData.forEach(function(file){
             //文件或文件夾路徑
             file.path = './'+projectData.name +'/'+ file.name;
             //根據type類型建立文件或文件夾
             file.content = file.content || '';

             switch(file.type){
                 case 'dir':
                     fs.mkdirSync(file.path);
                     break;

                 case 'file':
                     fs.writeFileSync(file.path,file.content);
                     break;
                 default:
                     break;
             }

        });
    }

}

二、自動打包多個文件

var fs = require('fs');
var filedir = './myProject/dist';

fs.exists(filedir,function(isExists){
    if(!isExists){
       fs.mkdirSync(filedir);
    }
    fs.watch(filedir,function(ev,file){
        //只要有一個文件發生了變化,咱們就須要對文件夾下的全部文件進行讀取、合併
        fs.readdir(filedir,function(err,dataList){
            var arr = [];
            dataList.forEach(function(file){
                if(file){
                    //statSync查看文件屬性
                    var info = fs.statSync(filedir + '/' +file);
                    //mode文件權限
                    if(info.mode === 33206){
                        arr.push(filedir + '/' +file);
                    }
                }
            });
            //讀取數組中的文件內容
            var content = '';
            arr.forEach(function(file){
                var c = fs.readFileSync(file);
                content += c.toString()+'\n';
            });
           //合併文件中的內容
           fs.writeFileSync('./myProject/js/index.js',content);

        })

    });
});

(7)使用node進行web開發

一、搭建一個http的服務器,用於處理用戶發送的http請求

//加載一個http模塊
var http = require('http');
//經過http模塊下的createServer建立並返回一個web服務器對象
var server = http.createServer();
//開啓 HTTP 服務器監聽鏈接,只有調用了listen方法之後,服務器纔開始工做
server.listen(8000,'localhost');
//服務器是否正在監聽鏈接
server.on('listening',function(){
    console.log("listening..........");
});
//每次接收到一個請求時觸發,每一個鏈接可能有多個請求(在 HTTP keep-alive 鏈接的狀況下)。
server.on('request',function(){
     res.write('<p>hello</p>');
     res.end();
});

二、request方法有兩個參數:request、response

1)request:http.IncomingMessage的一個實例,獲取請求的一些信息,如頭信息,數據等
httpVession:使用的http協議的版本
headers:請求頭信息中的數據
url:請求的地址
method:請求的方式

2)response:http.ServerResponse的一個實例,能夠向請求的客戶端輸出返回響應
write(chunk,encoding):發送一個數據塊到相應正文中
end(chunk,encoding):當全部的正文和頭信息發送完成之後調用該方法告訴服務器數據已經所有發送完成了,這個方法在每次完成信息發送之後必須調用,而且是最後調用。
statusCode:該屬性用來設置返回的狀態碼
setHeader(name,value):設置返回頭信息
writeHead(statusCode,reasonPhrase,headers)這個方法只能在當前請求中使用一次,而且必須在response.end()以前調用

三、使用fs模塊實現行爲表現分離

var http = require('http');
var url = require('url');
var fs = require('fs');

var server = http.createServer();
//html文件的路徑
var htmlDir = __dirname + '/html/';
server.on('request',function(request,response){
    var urlStr = url.parse(request.url);
    //根據pathname匹配對應的html文件
    switch(urlStr.pathname){
        case '/':
            sendData(htmlDir + 'index.html',request,response);
            break;
        case '/user':
            sendData(htmlDir + 'user.html',request,response);
            break;
        case '/login':
            sendData(htmlDir + 'login.html',request,response);
            break;
        default:
            //處理其餘狀況
            sendData(htmlDir + 'err.html',request,response );
            break;
    }
});

function sendData(file,request,response){
    //讀取文件,存在則返回對應讀取的內容,不存在則返回錯誤信息
    fs.readFile(file,function(err,data){
        if(err){
            response.writeHead(404,{
                'content-type':'text/html;charset=utf-8'
            });
            response.end('<h1>頁面不存在</h1>')
        }else{
            response.writeHead(200,{
                'content-type':'text/html;charset=utf-8'
            });
            response.end(data);
        }
    })
}
server.listen(8000,'localhost');
相關文章
相關標籤/搜索