생활코딩/WEBn

[Node.js] 기타 - read/write JSON, function import, css/js response, favicon

hayjo 2020. 9. 11. 23:32

~node.js로 로컬호스트에서 웹페이지 실습 겸 삽질해가며 깨달은 내용 기록~

 

json파일 가져오기

data  // 확장자 따로 설정하지 않았다

{
  "logo": "https://images.unsplash.com/photo-1592438710456-7ac899fc0b94?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
  "logosize": "width=\"300\" height=\"200\"",
   "description": "Big Tech, also known as the Tech Giants or S&P 5, are the largest and most dominant companies in the information technology industry, especially the \"Big Five\" American technology companies – Amazon, Apple, Alphabet, Facebook, and Microsoft."
}

read_json.js

/* Read 시에는 JSON.parse, Write 시에는 JSON.stringify로 변환한다 */
var fs = require('fs');

var dataBuffer = fs.readFileSync('./data');
var dataJSON = dataBuffer.toString();
var data = JSON.parse(dataJSON)
console.log(data);
/*
{
  logo: 'https://images.unsplash.com/photo-1592438710456-7ac899fc0b94?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80',
  logosize: 'width="300" height="200"',
  description: 'Big Tech, also known as the Tech Giants or S&P 5, are the largest and most dominant companies in the information technology industry, especially the "Big Five" American technology companies – Amazon, Apple, Alphabet, Facebook, and Microsoft.'
}
*/
console.log(data.logosize); // width="300" height="200"

 

json파일 저장하기

[참조] developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/JSON

/* Read 시에는 JSON.parse, Write 시에는 JSON.stringify로 변환한다 */
var fs = require('fs');

var jsonData = {"A": "a", "B": "b"};
var fileFormat = JSON.stringify(jsonData); // {"A":"a","B":"b"}
console.log(fileFormat.A); // undefined
fs.writeFile('filePath', fileFormat, 'utf8', function(err){
  console.log(err)
 }); // filePath 라는 파일에 {"A": "a", "B": "b"}가 저장됨

 

다른 js 파일에서 function import

[참조] stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files

 

In Node.js, how do I "include" functions from my other files?

Let's say I have a file called app.js. Pretty simple: var express = require('express'); var app = express.createServer(); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app...

stackoverflow.com

source.js    // import할 함수가 있는 js파일

module.exports = {
   hello: function(){
     console.log('Hello World!');
   }
};

혹은 이런 형식도 가능하다.

var M = {
   hello: function(){
     console.log('Hello World!');
   }
};

module.exports = M;

 

main.js     // 함수를 가져올 메인 js파일

var source = require('./source'); // 경로는 적당히 파일 위치에 따라 설정
source.hello();    // Hello World!

 

 

css/js 파일을 Node.js 서버 html 페이지에서 보여주려면 (without express)

-response로 보낸 html파일에 <link>나 <script> 태그로 연결된 파일은 자동 로딩이 안 된다.

-html에 css파일이나 js파일을 연결해두었으면 해당 파일을 response에서도 보내줘야 페이지가 정상 작동한다.

-일반적으로 express라는 프레임워크를 쓰는 모양인데 실습이라서 express 없이 구현해보았다.

[참조] stackoverflow.com/questions/40837359/node-js-not-serving-the-static-image?noredirect=1&lq=1

[참조] github.com/nodejs/help/issues/1771

[참조] stackoverflow.com/questions/12134554/node-js-external-js-and-css-files-just-using-node-js-not-express

 

-입력 url 파싱해서 pathname, extension 얻어낸 다음, 아래 로직처럼 확장자에 따라 각각 처리한다.

if(ext === 'css'){
  css 처리(header에 'content-Type' 명시, response.write로 readFile해서 데이터 넘겨주기)
} else if(ext === 'js'){
  js 처리
} else {
  html & not found 처리
}

 

main.js

var http = require('http');
var fs = require('fs');
var url = require('url');

var app = http.createServer(function(request, response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var pathname = url.parse(_url, true).pathname;
    if(pathname !== '/'){
      var ext = pathname.split('.').splice(-1)[0];
    } else {
      var ext = '';
    }

    fs.readdir('./data', function(err, dataList){   // 작업에 dir list가 필요해서 그냥 이 안에다가 함수 열었음..
      if(ext){     // 확장자가 있으면! 다른 html 파일들은 확장자 안 달아서 확장자 있으면 다른 파일임
        if(ext === 'css'){                                                // css 파일이면
          response.writeHead(200, {'Content-Type': 'text/css'});           // css Type 표시
        } else if(ext === 'js'){                                          // js 파일이면
          response.writeHead(200, {'Content-Type': 'text/javascript'});    // js Type 표시
        }
        response.write(fs.readFileSync(__dirname + pathname, 'utf-8'));    // [!]파일 보내주는 부분
        response.end();                                                    // response 완료
      } else {
        if(pathname === "/" && title === undefined){      // 홈으로 들어갔으면 (index.html)
            console.log();
            var template = templates.get('home', `./home`, dataList);
            response.writeHead(200);                      // 전송 !
            response.end(template);
        } else if(dataList.indexOf(title) >= 0){          // 나머지 dataList 부분 접속이면
            var template = templates.get(title, `data/${title}`, dataList);
            response.writeHead(200);                      // 해당 데이터 만들어서 전송
            response.end(template);
        } else {                                          // 확인불가 페이지는 404 error
          response.writeHead(404);
          response.end('Page Not Founded');
        }
      }
    })
});
app.listen(3000);

 

favicon.ico 비활성화

-파비콘(favicon): 웹 브라우저 주소창에 표시되는 아이콘

 

▲ W 모양 로고가 위키백과의 파비콘이다.

 

-위에서 html 아닌 파일 로딩을 완료했더니, 페이지 이동시마다 avicon.ico를 요청한다. 물론 만든 적이 없으니 오류가 난다.

-보통은 있는게 좋다고 하는데, 예상외의 확장자라 자꾸 실습을 방해해서 비활성화했다.

[참조] stackoverflow.com/questions/1321878/how-to-prevent-favicon-ico-requests

 

How to prevent favicon.ico requests?

I don't have a favicon.ico, but my browser always makes a request for it. Is it possible to prevent the browser from making a request for the favicon from my site? Maybe some META-TAG in the HTML h...

stackoverflow.com

 

html 파일 <head> 부분에 아래 코드를 추가하면 비활성화된다.

<link rel="icon" href="data:,">