美文网首页
NODE.js学习笔记

NODE.js学习笔记

作者: _李杨 | 来源:发表于2017-02-23 21:52 被阅读0次

    fs模块,用于读写文件.

    异步读取代码为:

    var fs = require('fs');
    fs.readFile('sample.txt','utf-8',function(err,data){
      if(err){
        console.log('出错了');
      } else{
        console.log(data);
      }
    });
    

    同步读取代码为:

    var fs = require('fs');
    try {
      var data = fs.readFileSync('sample.txt','utf-8);
      console.log(data);
    } catch {
      console.log('出错了');
    }
    

    异步写入代码为:

    var fs = require('fs');
    var data = 'hello,node.js';
    fs.writeFile('output.txt',data,function(err){
      if(err){
        console.log('出错了');
      } else {
        console.log('ok.');
      }
    });
    

    同步写入代码为:

    var fs = require('fs');
    var data = 'hello,node.js';
    fs.writeFileSync('output.txt',data);
    

    注:执行写入代码时,若输出文件不存在,则会创建。若存在,则会覆盖原文件内容。
    异步读取文件信息:

    var fs = require('fs');
    fs.stat('samplt.txt',functon(err,stat) {
      if(err) {
        console.log(err);
      } else {
        console.log('isFile: ' + stat.isFile());
        console.log('isDirectory: ' + stat.isDirectory());
        if(stat.isFile()) {
          console.log('size: '+ stat.size);
          console.log('birth time: ' + stat.birthtime);
          console.log('modified time: ' + stat.mtime);
      }
    });
    

    同步读取文件信息:

    var fs = require('fs');
    try {
        var stat=fs.statSync('fileRead.txt');
        // 是否是文件:
        console.log('isFile: ' + stat.isFile());
        // 是否是目录:
        console.log('isDirectory: ' + stat.isDirectory());
        if (stat.isFile()) {
            // 文件大小:
            console.log('size: ' + stat.size);
            // 创建时间, Date对象:
            console.log('birth time: ' + stat.birthtime);
            // 修改时间, Date对象:
            console.log('modified time: ' + stat.mtime);
        }
    } catch (err) {
        // 出错了
        console.log(err);
    }
    

    流读取文件:

    var fs = require('fs');
    var rs = fs.createReadStream('sample.txt','utf-8');
    rs.on('data',function(chunk) {
      console.log('DATA: ');
      console.log(chunk);
    });
    rs.on('end',function()  {
      console.log('END');
    });
    rs.on('err',function(err) {
      console.log('ERROR: ' + err);
    });
    

    流写入文件:

    var fs = require('fs');
    var ws1 = fs.createWriteStream('output1.txt,'utf-8');
    ws1.write('使用Stream写入文本数据...\n');
    ws1.write('END.');
    ws1.end();
    
    var ws2 = fs.createWriteStream('output2.txt');
    ws2.write(new Buffer('使用Stream写入二进制数据...\n','utf-8');
    ws2.write(new Buffer('END',"utf-8');
    ws2.end();
    

    流复制文件:

    var fs = require('fs');
    var rs = fs.createReadStream('sample.txt');
    var ws = fs.createWriteStream('copied.txt');
    rs.pipe(ws);
    

    默认情况下,当Readable流的数据读取完毕,end事件触发后,将自动关闭Writable流。如果我们不希望自动关闭Writable流,需要传入参数:

    readable.pipe(writable,{end:false});
    

    建立一个http服务器:

    var http = require('http');
    //创建http server 传入回调函数,该函数接收request 和 response对象
    var server = http.createServer(function(request,response){
      //获得http请求的method 和 url
      console.log(request.method + ':' + request.url);
      //将响应200写入response,同时设置Content-Type:text/html
      response.writeHead(200,{'Content-Type' : 'text/html'});
      //将http响应的html内容写入response
      response.end('<h1>hello world!</h1>');
    });
    //服务器监听8080端口
    server.listen(8080);
    //服务器启动成功,则打印以下内容
    console.log('Server is running at http://127.0.0.1:8080/')
    

    建立一个http文件服务器

    var fs = require('fs'),
          http = require('http'),
          url = require('url'),
          path = require('path');
    //命令行参数获取root目录,默认当前目录
    var root = path.resolve(process.argv[2] || '.');
    var server = http.createServer(function(request,response){
      //解析请求url 获取路径
      var pathname = url.parse(request.url).pathname;
      //合并路径,获取文件真实路径
      var filepath = path.join(root,pathname);
      //读取文件信息
      fs.stat(filepath,function(err,stat) {
        //如果出错
        if(!err) {
          console.log('404' + request.url);
          //返回404
          response.writeHead(404);
          //如果路径是文件
        } else if(stat.isFile()) {
          console.log('200' + request.url);
          //返回200 
          response.writeHead(200);
          //文件内容发送到 response
          fs.createReadStream(filepath).pipe(response);
          //如果路径是目录
        } else if (stat.isDirectory()) {
          //创建一个默认文件名数组 
          var defpath = ['index.html','defaule.html'];
          //遍历数组
          for(var i = 0; i < defpath.length; i++) {
            //获取新的文件路径
            var deffile = path.join(root,deffile[i]);
            //如果路径存在
            if (fs.existsSync(deffile)) {
              console.log('200' + request.url);
               //返回200 
              response.writeHead(200);
              //文件内容发送到response
              fs.createReadStream(deffile).pipe(response);
            }
          }
        }
      });
    });
    
    server.listen(8080);
    console.log('Server is running at http://127.0.0.1:8080');
    

    相关文章

      网友评论

          本文标题:NODE.js学习笔记

          本文链接:https://www.haomeiwen.com/subject/jdcbwttx.html