Node.js入门(二)——简单读写文件

来源:互联网 发布:工商名录采集软件 编辑:程序博客网 时间:2024/06/03 21:39

前言

本篇小编主要介绍node.js读取html,并且想html文件写入的方式。

内容

目录结构 file文件下存放了login.html,module文件下存放optfile.js
这里写图片描述

1.optfile.js

var fs=require('fs');module.exports={    readfileSync:function(path){//同步读取       var data=fs.readFileSync(path,'utf-8');       console.log(data);          console.log("同步方法执行完毕");    },    readfile:function(path){ //异步执行        fs.readFile(path,function(err,data){            if(err){                console.log(err);            }else{                console.log(data.toString());            }        });        console.log("异步方法执行完毕");    }}

2.主文件JS

var http=require('http');var optfile=require('./module/optfiles');http.createServer(function(request,response){    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});    if(request.url!="/favicon.ico"){//清除第二次访问        optfile.readfileSync('./file/login.html');        response.end('ok');        console.log('主程序结束');    }}).listen(8000);console.log("这个路由");

结语

感谢大家浏览,希望带给你帮助!

原创粉丝点击