zoukankan      html  css  js  c++  java
  • 异步同步读取文件内容对比

     1 /**
     2  * Created by Administrator on 2016/8/3.
     3  */
     4 var http = require("http");
     5 //Node 导入文件系统模块
     6 var fs = require("fs");
     7 function start(req, res){
     8     res.writeHead(200, {"Content-Type": "text/plain"});
     9     res.write("异步读取文件和同步读取文件的对比!");
    10     res.end("over");
    11 }
    12 //创建一个http服务器,并监听端口号为3001,host为127.1.1.1
    13 var server = http.createServer(start).listen("3001","127.1.1.1",function(){
    14     var port = server.address().port;
    15     var host = server.address().address;
    16     console.log("应用实例,访问地址为 http://%s:%s", host, port);
    17 });
    18 //异步读取[非阻塞]
    19 console.log("异步开始:");
    20 //异步读取文件内容的函数: readFile()
    21 fs.readFile("index.txt", "utf-8", function(err, data){
    22     if(err){
    23         console.log(err);
    24     }else{
    25         console.log(data);
    26     }
    27 });
    28 console.log("end异步");
    29 //同步读取[阻塞,阻塞之后代码的执行]
    30 console.log("同步开始:");
    31 //同步读取文件内容的函数: readFileSync()
    32 var data = fs.readFileSync("index.txt", "utf-8");
    33 console.log(data);
    34 console.log("end同步");
  • 相关阅读:
    从域名锁定该网站所在城市
    微信接口开发 2----接收微信接口返回的数据
    微信接口开发1--向微信发送请求--获取access_token
    MVC-前端设计
    MVC-第一个简单的程序
    MVC-基础02
    MVC-基础01
    表值函数
    视图

  • 原文地址:https://www.cnblogs.com/lee90/p/5732692.html
Copyright © 2011-2022 走看看