본문 바로가기
카테고리 없음

[JavaScript]서버 만들기, html

by 왹져박사 2023. 5. 18.
728x90

npm Init

배포할때 설명

yes

json파일 만들어짐

 

https://nodejs.org/api/modules.html#exports-shortcut

 

Modules: CommonJS modules | Node.js v20.2.0 Documentation

Modules: CommonJS modules# CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes. In Node.js, each file is treated as a separate mo

nodejs.org

 

node는 key와 value로 이루어져있기 때문에 두 방법으로 사용 가능

import를 사용하기 위하여 json파일에 type추가

웹에서 코드

http://about.black/

 

 

윈도우 사용중인 포트 확인

netStat -ano

특정 포트 존재 확인하기

netstat -ano |findstr 8080

존재x, 사용가능

 

연결중, 아무것도 없어 안나옴

 

나왔지만 인코딩 안됨

 

http node 한글 인코딩

    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });

//모듈 가져오기
const http = require('http');

//서버를 만들고 클라이언트에 대한 요청을 처리할 콜백 메서드를 등록
const server = http.createServer((req, res) => {
    //인코딩 정의 한글
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    
    //res객체에 값을 응답할 값을 쓴다
    res.write('왹져박사의 서버에 오신 것을 환영합니다!');

    //응답을 종료한다
    res.end();
});

//포트 변수 초기화
const port = 8080;

//서버 실행시 호출될 콜백을 등록
server.listen(port, ()=>{
    console.log(`서버가 시작 되었습ㄴ다. port : ${port}`);
});

 

const { error } = require('console');
const http = require('http');
const port = 8080;

//서버를 만들고 클라 요청을 받아 응답
const server = http.createServer((req, res)=>{
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('왹져박사의 서버입니다');
    res.end();  //응답 종료
});

server.on('listening', ()=>{
    console.log(`서버가 시작 되었습니다. port: ${port}`);
});     //서버가 시작 되면 호출

server.on('error', ()=>{
    console.error(error);
});     //서버에 문제가 있으면 호출

server.listen(port);    //포트 열기

 

html

 

!하고 enter치면 자동으로 완성된다.

예전에 html 배울때는 메모장으로 다 적고 확장자 html로 바꿔 저장했다..세상 좋다

 

buffer를 16진수로 처리해서 나옴

 

toString()으로 문자열로 변환

 

const { error } = require('console');
const http = require('http');
const readFile = require('./test');
const port = 8080;

//서버를 만들고 클라 요청을 받아 응답
const server = http.createServer((req, res)=>{
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    readFile('./index.html', (err, data)=>{
        res.write(data);
        res.end();  //응답 종료
    });
    res.write('왹져박사의 서버입니다');
});

server.on('listening', ()=>{
    console.log(`서버가 시작 되었습니다. port: ${port}`);
});     //서버가 시작 되면 호출

server.on('error', ()=>{
    console.error(error);
});     //서버에 문제가 있으면 호출

server.listen(port);    //포트 열기
const fs = require('fs');

fs.readFile('./index.html', (err, data)=>{
    console.log(data.toString());
});


function readFile(path, callback)
{
    fs.readFile('./index.html', callback);
}

//테스트
// readFile('./index.html', (err, data)=>{
//     console.log(data.toString());
// });

module.exports = readFile;

728x90