nodeJS學習筆記

nodeJS學習筆記javascript

// node中的全局對象
    //console.log() 
    // 定時器:setTimeout setInterval clearTimeout clearInterval
    // 路徑: __dirname __filename
    // global node.js全局對象是 global  javascript的全局對象是window

// node中的模塊 module
    // const counter = require('./node/stuff.js') //模塊導入

    // console.log(counter.counter([0.1, 21, 215, 345, 345, 154, 12]), counter.sun())

// 事件模塊 

    //  引入事件模塊
    /* const events = require('events'); //引入事件模塊
        

    //  實例化EventEmitter對象
    var myEmitter = new events.EventEmitter() 

    //  註冊事件
    myEmitter.on('someEvent',function(msg){ 
        setImmediate(()=>{ //異步事件
            console.log('註冊事件', msg)
        })
    })

    // 觸發事件
    myEmitter.emit('someEvent','hello! node.js')//第一個參數是事件名,第二個是實參

    console.log('dssadas') */

// 文件系統模塊
    // 讀寫文件
        //讀取文件(fs.readFile)
        //寫入文件(fs.writeFile)
 
    //1.引入文件系統模塊
    //  const fs = require('fs');
    /*
        //2.經過對象調用方法 同步讀取文件
        var user = fs.readFileSync('user.json','utf-8')

        console.log(user)
        //3.同步寫入文件
        fs.writeFileSync('user.json',24) */

    //異步讀寫文件
        /* 
        fs.readFile('user.jso','utf-8',function(err,data){
            if(err){
                console.log(err)
            }
                console.log(clcledata)
            }) */
       // 異步必須有回調函數
           /*  fs.readFile('user.txt', 'utf-8', function (err, data) {
                if (err) {
                    console.log(err)
                }
                console.log(data)
            })

            fs.readFile('user.txt','utf8',function(err,data){
                if(err) throw err;
                fs.writeFile('users.txt',data,function(){

                })
            }) 
       
        nodenode
        console.log(1121) */

//刪除或者增長文件
        const fs = require('fs');
    //調用刪除方法
       /*  fs.unlink('user.txt',function(){
            if(err) throw err;
            console.log('文件刪除成功!')
        }) */
        // fs.mkdirSync('stuff')
        // fs.rmdirSync('stuff')
    //異步建立和刪除文件夾
        //添加文件夾
        /* fs.mkdir('stuff',function(){
            fs.writeFile('read.txt',`{ "xiaogeng":{"name": "xiaogeng","age": 24, "love": "no"}}`,function(err,data){
                if(err) throw err;
                console.log(data)
            })
        }) */
        //刪除文件夾 文件夾內若是有文件,則須要先把文件刪除
        /* fs.unlink('stuff/read.txt',function(err,data){
            if(err) throw err;
            console.log('文件刪除成功!')
            fs.rmdir('stuff',function(err,data){
                if (err) throw err;
                console.log('文件夾刪除成功!')
            })
        }) */

搭建簡單的服務器html

//引入服務器模塊
const http = require('http')
//建立服務器方法
var server = http.createServer(function (req, res) {
    console.log("客戶端向服務器發送請求:" + req.url);
    res.writeHead(200,{"Content-type":'text/plain'})
    res.end('../index.html')
})
//服務器對象監聽服務器地址以及端口號
server.listen(8088, '192.168.0.105')

console.log('server is running......')
// 讀寫數據流
const fs = require('fs');
//讀數據流
    /* let myReadSteam = fs.createReadStream(__dirname+'/user.txt','utf8')

    myReadSteam.on('data',function(chunk){
        console.log('=============一部分數據=============')
        console.log(chunk)
    }) */

let myReadSteam = fs.createReadStream(__dirname + '/user.txt', 'utf8')

// let myWriteSteam = fs.createWriteStream(__dirname+'/wirte2.txt')

// myReadSteam.pipe(myWriteSteam)

// let time = 0;
// myReadSteam.on('data', function (chunk) {
//     time++
//     console.log('============='+ time +'部分數據=============')
//     myWriteSteam.write(chunk)
// })

var http = require('http');

var server = http.createServer(function(req,res){
    res.writeHead(200,{'Content-type':'text/plain'})
    let myReadSteam = fs.createReadStream(__dirname + '/user.txt', 'utf8')
    myReadSteam.pipe(res)
})

server.listen(5000,'192.168.0.105')
const http = require('http')

let server = http.createServer(function(req,res){
    res.writeHead(200,{'Content-type':'text/html'});
    var myReadStream = fs.createReadStream(__dirname + '/dist/index.html', 'utf8');
    myReadStream.pipe(res)
}) 

server.listen('3000','192.168.0.105')
const http = require('http')

const fs = require('fs')

let server = http.createServer(function(req,res){
    if(req.url!=='/favicon.ico'){
        console.log('用戶正在向客戶端發送請求:' + req.url)

         if (req.url === '/index' || req.url === '/') {
             res.writeHead(200, {
                 'Content-type': 'text/html'
             })
             var myReadeSteam = fs.createReadStream('index.html','utf-8')
             myReadeSteam.pipe(res)
         } else if (req.url === '/home') {
             res.writeHead(200, {
                 'Content-type': 'text/html'
             })
            
            var myReadeSteam = fs.createReadStream('home.html', 'utf-8')
            myReadeSteam.pipe(res)
         } else if (req.url === '/app/app') {
             res.writeHead(200, {
                 'Content-type': 'application/json'
             })
             var data = [{
                 "name": "xiaogeng"
             },
              {
                 "age": "24"
             }];
             res.end(JSON.stringify(data))
         }
    }
})

console.log('server is running.......')

server.listen(3000,'192.168.0.105')
//引入express框架
const express = require('express');
//實例化express對象
const app = new express()

//經過對象調用express方法
// 根據用戶訪問的地址返回對應信息
    /* app.get('/',function(req,res){ //建立訪問路徑
        console.log(req.url)
        res.send('this is home page') //返回信息
    })

    app.get('/app', function (req, res) { //路由
        console.log(req.url)
        res.send('this is app page')
    }) */
//路由參數
app.get('/app/:id', function (req, res) { //路由
    console.log(req.url)
    res.send('this is app page is :'+req.params.id)
})

//監聽服務器端口
app.listen(5000)
// 應用EJS 配置視圖引擎
app.set('view engine','ejs')
//路由參數
app.get('/app/:id',function(req,res){
    var data = [{age:25,name:['xiaogeng','loveyou']},{age:25,name:['genggeng','aini']}]
    res.render('app',{websiteName:req.params.id,data:data})
})

//監聽服務器端口
app.listen(5000)
<h1>this is <%= websiteName %> page!</h1>
    <h2>我的介紹:</h2>
    <ul>
        <% data.forEach(function(item){ %>
            <li><%= item.name %></li>
            <li><%= item.age %></li>
        <% })%>
    </ul>
相關文章
相關標籤/搜索