1. 程式人生 > >Node.js http fs

Node.js http fs

 

 

const http=require('http');
const fs=require('fs');

var server = http.createServer(function(req, res){
    var file_name = './www' + req.url;
    // req.url => '/index.html'
    // 讀取 => './www.index.html'
    // './www' + req.url
    // 使用者請求了某個url (req.url), 比如 index.html,實際就是在伺服器的.www資料夾裡訪問了index.html
fs.readFile(file_name, function(err, data){ if(err){ res.write('404'); }else{ res.write(data); } res.end(); }) }); server.listen(8080);

 

const fs = require('fs');

// 檔案操作 fs => file syestem

// fs.readFile(檔名, 回撥)
fs.readFile('aaa.txt', function
(err, data){ if(err){ console.log('讀取失敗'); }else{ console.log(data.toString()); } }); // fs.writeFile(檔名, 內容, 回撥) fs.writeFile("bbb.txt","gdgignrgkwng", function(err){ console.log(err); })