에디터로 아래와 같은 코드를 작성하고 파일이름은 main.js로 저장

var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request,response){
    var url = request.url;
    if(request.url == '/'){
      url = '/index.html';
    }
    if(request.url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    response.end(fs.readFileSync(__dirname + url));

});
app.listen(3000);

NodeJs로 main.js를 실행시킨다

cmd명령어 =

cd (main.js가 있는 경로) -> node main.js

 

이렇게 했을 때

 

http://localhost:3000 을 입력하면 index.html이 실행되는 것을 알 수 있다

 

코드를 약간만 수정해보자

var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request,response){
    var url = request.url;
    if(request.url == '/'){
      url = '/index.html';
    }
    if(request.url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    console.log(__dirname + url);
    response.end(fs.readFileSync(__dirname + url));

});
app.listen(3000);

__dirname + url의 값이 무엇이 나오는지 결과를 보면

검색한 곳의 경로가 나오게 된다

ex) C:\Users\사용자\바탕화면\nodejs/2.html

 

response.end의 괄호에 'A : ' +url 값을 넣어보면

    response.end('A : '+url);

3.html에 있을 때 화면에 A : /3.html 가 출력된다

 

'휴지통 > Node.Js' 카테고리의 다른 글

공부(6)  (0) 2021.08.24
공부(5)  (0) 2021.08.24
공부(4)  (0) 2021.08.23
공부(3)  (0) 2021.08.23
공부(2)  (0) 2021.08.23

아톰 에디터를 이용하여 웹 개발 포스팅을 할 예정

 

아톰 다운로드 링크 : https://atom.io/

 

A hackable text editor for the 21st Century

At GitHub, we’re building the text editor we’ve always wanted: hackable to the core, but approachable on the first day without ever touching a config file. We can’t wait to see what you build with it.

atom.io

 

+ Recent posts