node基础07:写文件

1.writeFile

//server.js

var http = require("http");
var writefile = require("./writefile");

http.createServer(function(res, res){
    res.writeHead(200, {"Content-Type":"text/html; charset=uf-8"});
    if (res.url!=="/favicon.ico") {
        console.log('begin visit');
        res.write('hello world');
        writefile.writefile('./test.txt', 'gaoxiong'); //如果文件路径存在则添加数据,如果不存在则新建文件并且添加数据
        res.end('end');
    }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//writefile.js
var fs = require("fs");
module.exports = {
    //异步方式
    writefile:function(path, data){
        fs.writeFile(path, data, function(err){
            if (err) {
                throw(err)
            } else{
                console.log('saved success');
            }
        })
    },
    //同步方式
    writefileSync:function(path, data){
        fs.writeFileSync(path, data);
        console.log('同步写文件完成')
    }
}
原文地址:https://www.cnblogs.com/noper/p/6244589.html