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的文件说明写入成功;如下图:

原文地址:https://www.cnblogs.com/dxsghr/p/6808263.html