555
e

url-module.js 1.2KB

1234567891011121314151617181920212223242526272829303132
  1. //var url = require('url');
  2. //var adr = 'http://localhost:1337/index.html?student=홍길동&classname=nodejs';
  3. //var q = url.parse(adr, true);
  4. //
  5. //console.log(q.host); // returns 'localhost:1337'
  6. //console.log(q.pathname); // returns '/index.html'
  7. //console.log(q.search); // returns '?student=홍길동&classname=nodejs'
  8. //
  9. //var qdata = q.query; // returns an object: { student: '홍길동', classname: 'nodejs' }
  10. //console.log(qdata.classname); // returns 'february'
  11. var http = require('http');
  12. var url = require('url');
  13. var fs = require('fs');
  14. http.createServer(function (req, res) {
  15. var q = url.parse(req.url, true);
  16. // '.'은 현재 디렉토리를 의미하며, ./nodejs.html은 현재 디렉토리의 nodejs.html파일
  17. var filename = "." + q.pathname;
  18. console.log(filename);
  19. fs.readFile(filename, function(err, data) {
  20. if (err) {
  21. res.writeHead(404, {'Content-Type': 'text/html'});
  22. return res.end("404 Not Found");
  23. }
  24. res.writeHead(200, {'Content-Type': 'text/html'});
  25. res.write(data);
  26. return res.end();
  27. });
  28. }).listen(1337); // listen(1337, '127.0.0.1') 와 동일
  29. console.log('Server running at http://127.0.0.1:1337/');