먼저 다음과 같이 public디렉토리 ,profile.html,./public/index.html파일을 만듭니다.
profile.html파일과 index.html파일의 내용은 아래에 있습니다.
컬러 강조된 부분은 새로 추가된 코드 입니다.
First, create the public directory, profile.html, and ./public/index.html files as follows.
The contents of the profile.html file and index.html file are below.
All parts highlighted in color are newly added codes.
![]() | ![]() |
1.app.use(express.static(__dirname+”/public”));
– 브라우저에서 localhost:3000실행시 public디렉토리 내의 index.html파일이 실행 됩니다.
– 제가 사용하는 PC의 절대경로는 다음과 같습니다.E:\nodejs\lec\public
– 보라색은 localhost:3000 실행시 ‘Express Hello World’를 출력하며 동일한 기능이라 코멘트 처리 했습니다.
When you run localhost:3000 in your browser, the index.html file in the public directory is executed.
The absolute path on the PC I use is as follows: E:\nodejs\lec\public
The purple color outputs ‘Express Hello World’ when running localhost:3000, and has been commented out as it is the same function.
2.console.log(__dirname);
– ‘__dirname’ 디렉토리 환경변수로써 console.log(__dirname);을 실행하면 현재 디렉토리 경로를 출력합니다.
When you run console.log(__dirname); with the ‘__dirname’ directory environment variable, the current directory path is displayed.
3.app.get(“/profile”,(req,res)=>{}
– ‘localhost:3000/profile’을 실행했을 때 현재 디렉토리에서 profile.html을 실행 합니다.
When executing ‘localhost:3000/profile’, profile.html is executed in the current directory.
//server_ex.js
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
/* routing */
app.use(express.static(__dirname+"/public"));
//디렉토리 환경변수
//Directory environment variable
console.log(__dirname);
/*
app.get('/',(req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Express Hello World!\n');
});
*/
//text
app.get('/about',(req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Express About!\n');
});
app.get('/random.text', function (req, res) {
res.send('Express random.text');
});
//file
app.get("/profile",(req,res)=>{
res.sendFile(__dirname + "/profile.html");
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`CommonJS(Express) Server is running on port ${PORT}`);
});
public/index.html
<html>
<head>
<title>index.html</title>
</head>
<body>
index 인덱스
</body>
</html>
profile.html
<html>
<head>
<title>profile.html</title>
</head>
<body>
profile 프로필
</body>
</html>