web前端一起努力Node

Node.js

2018-08-30  本文已影响0人  追逐_chase

Node.js是什么

安装
文件数据操作

// 浏览器中的javaScript是没有文件操作的能力的

 // 但是node中的JavaScript具有文件操作的能力

 //fs是 fileSystem的简写 就是文件系统的意思

/*
* 在node中 如果想要进行文件操作,就必须引入fs这个核心模块
*
* 在fs这个核心模块中,提供了所有的文件操作相关的API
*
* 例如:fs.readFile就是用来读取文件的
*
* */

//加载 fs 的核心模块

 var fs =  require("fs");

 // 2.读取文件

/*
* 第一个参数 是路径
*
* 第二个参数 会回调函数
*
* error 错误(读取失败)
*
* data 数据 (读取成功)
*
* */

fs.readFile("data/hello.txt",function (error,data) {

    /*
    * data有数据的话 打印的是二进制数据
    *
    * 要通过toString方法转化成 我们认识的字符串
    *
    * */
    // 打印结果 <Buffer 0a 0a e8 bf 99 e6 98 af e4 b8 80 e4 b8 aa 20 e6 96 87 e4 bb b6 e8 af bb e5 8f 96>
    console.log(data.toString());
});


创建node服务器

//1.加载核心模块

var htt = require("http");

//2.使用htt.createServer()创建一个web服务器

var server  = htt.createServer();

//3.服务器   对数据服务

/*
* 发送请求
*
* 接收请求
*
* 处理请求
*
*
* 给个反馈(发送响应)
*
* */

//  注册  request请求事件 当客户端请求过来,就会自动触发服务器的request请求事件

// 然后 执行第二个参数:回调处理
/*
* 2个参数
* Request 请求对象, 用来获取 客服端的请求信息
*
* Response 响应对象,可以用来给客户端发送响应消息
*
* */
server.on("request",function (request,response) {

    //路径
    console.log("收到客户端的请求了" + request.url);

    // 根据不同的请求路径  响应不同的结果

//   /index

// /login  登录

// /register  注册

    if (request.url == "/index") {

        response.write("home");
        console.log("看看有没");

    } else if (request.url == "/login"){
        response.write("login");
    } else if (response.url == "/register"){
        response.write("register");
    } else {
        //  response 对象有一个方法:write 可以用客户端发送响应数据
        //write可以使用多次,但是最后一定要使用end来结束响应,否则客户端会一直等待(就是重启服务器)


        response.write("hello");
    }

    //结束响应,可以返回数据给客户端了
    response.end();

});

//4.绑定端口号,启动服务器

server.listen(3000,function () {
    //回调函数

    console.log("服务器启动成功");

});
// control + c 关闭服务

//IP地址 和 端口号

// ip地址用来定位计算机
// 端口号用来定位具体的应用程序
//所有的通信软件都会占用一个端口号
// 端口号的范围 0-65536
 


不同模块之间的通信
上一篇 下一篇

猜你喜欢

热点阅读