zoukankan      html  css  js  c++  java
  • NodeJs学习(操作文件)(二)

    var fs = require("fs");  //操作文件必须要引入的模块;
    module.exports = {
        //同步读取文件
        readFileSync:function(res){
            var data = fs.readFileSync('./template/index.html','utf-8') //读取文件,第一个参数为模板文件路径。第二个参数为编码
            res.write(data);
        },
        //异步读取文件
        readFile:function(file,res){
            fs.readFile(file,'utf-8',function(err,data){//有三个参数,前俩个一样,最后多了一个回调函数
                res.write(data);
                res.end();
            })
        }
    }

    上面为读取文件的操作:一种是同步读取,一种是异步读取!(文件名为fills.js);

    目录结构为上图这样;还需要创建一个index.html(里面内容随意写就可以)和服务helloword.js文件;

    helloword.js文件代码为:

    var http = require('http');
    var fill = require('./fill/fills.js')
    //创建服务
    http.createServer(function(request,response){
        response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
        // fill.readFileSync(response);//同步读取
        fill.readFile('./template/index.html',response)//异步读取
        // response.end(); //应为是异步读取所以response.end()要放到fills.js里的readFileli面去
    }).listen(8030);

    进行写入操作:

    修改fills.js代码:

     1 var fs = require("fs");
     2 module.exports = {
     3     //同步读取文件
     4     readFileSync:function(res){
     5         var data = fs.readFileSync('./template/index.html','utf-8') //读取文件,第一个参数为模板文件路径。第二个参数为编码
     6         res.write(data);
     7     },
     8     //异步读取文件
     9     readFile:function(file,res){
    10         fs.readFile(file,'utf-8',function(err,data){//有三个参数,前俩个一样,最后多了一个回调函数
    11             res.write(data);
    12             res.end();
    13         })
    14     },
    15     //写入文件
    16     //fs.writeFile(file,data[,option],callback)有四个参数
    17     //第一个参数为写入文件路径;第二个参数为写入的内容;第三个参数为编码;第四个参数为一个回调函数
    18     writeFile:function(file,res){
    19         fs.writeFile(file,'abc','utf-8',function(err){
    20             if(err) throw err;  // 如果有错误抛出一个异常
    21             res.write('写入成功!!');
    22             res.end();
    23         }) 
    24     },
    25 }

    helloword.js代码修改:

    1 var http = require('http');
    2 var fill = require('./fill/fills.js')
    3 //创建服务
    4 http.createServer(function(request,response){
    5     response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
    6     fill.writeFile('./files/test.txt',response)
    7 }).listen(8030);

    在node后台run一下的话;会在files文件夹下生成test.txt的文件说明写入成功;如下图:

  • 相关阅读:
    【C/C++】Dijkstra算法的简洁实现
    【数学建模】图论方法的数学模型
    【数学建模】模糊数学模型详解
    【数学建模】基于问题的线性规划和混合整数规划求解
    【机器学习】非常全的机器学习资源汇总
    【数据结构】数据结构中的各种树详解
    【数据结构】八大排序算法
    【数据结构】七大查找算法
    【数学建模】MATLAB语法
    【论文阅读】Sequence to Sequence Learning with Neural Network
  • 原文地址:https://www.cnblogs.com/dxsghr/p/6808263.html
Copyright © 2011-2022 走看看