StoryCode

'Node.js'에 해당되는 글 8건

  1. 연습) Hello, World.
  2. 각종 설치 참조
  3. Atom 설치
  4. 설치 (Windows)
  5. 내장 모듈
  6. Process 객체, exports 객체
  7. API
  8. 설치

연습) Hello, World.

Node.js
반응형

1. HTTP Methods(HTTP-Verbs) - GET, POST, PUT, PATCH, DELETE

HTTP Methods ( = HTTP Verbs)의 종류 : GET, POST, PUT, PATCH, DELETE

참고) resource 의 종류 : html, binary(image, sound), db (db, json, xml, flat)

 

GET : 조회

POST : 등록

PUT : 수정(없을시 등록). 한 컬럼만 업데이트시에도 모든 컬럼 업데이트.

PATCH : 수정. 한 컬럼만 업데이트시 한 컬럼만 업데이트.

DELETE : 삭제

 

2. Express로 서버 실행하기 (GIT : https://github.com/a-mean-blogger/hello-world/tree/eaa13c5356ebaa06bd14df80bee96edb085fac46)

 

$ git clone https://github.com/a-mean-blogger/hello-world.git
$ cd hello-world
$ git reset --hard eaa13c5
$ npm install
$ atom .

 

위 git clone 없이 직접 해보기

$ git init

$ npm init

$ touch index.js

$ npm install --save express

$ atom . ( 혹은 vi index.js )

   index.js 에 아래 내용 입력

   -----------------------------------------

var express = require('express')
var app = express();

app.get('/', function (req, res) // '/' 로 get 요청시
{
  res.send('Hello World!');
})

app.listen(3000, function()
{
  console.log('Server On!');
})

   -----------------------------------------

$ node index.js

   Server On!

그리고, Chrome> localhost:3000 으로 접속하면, Hello World! 가 보인다.


3. Static 폴더 추가하기

index.js 를 아래내용으로 변경

// index.js

var express = require('express');
var app = express();

 

// __dirname = 현재 실행 위치

// app.use : 브라우저에서, / 으로 접속하면 /public/ 에 변경접속, /css 으로 접속하면 /public/css 으로 변경접속

// css 나 html 같은 고정 파일 위치에 사용한다. 아래 "4. EJS로 Dynamic Website" 에서 <link> 태그에 public 이 없어도 public 을 참조하게 된다.
app.use(express.static(__dirname + '/public')); 

app.listen(3000, function(){
 console.log('Server On!');
});

 

 

$ node index.js #재실행

   Server On!

그리고, Chrome> localhost:3000 으로 접속하면, 주황색 Hello World! 가 보인다.

 


4. EJS로 Dynamic Website 만들기

* 용어.EJS) EJS는 Embedded Javascript의 약자로 Express에서 dynamic website를 만들기 위해 template으로 사용되는 파일(확장자 이름은 .ejs)입니다.

 

$ npm install --save ejs # ejs 설치

 

> views 폴더와 views/hello.ejs 파일 추가

 

> index.js 내용 변경 -----------------------------------------

// index.js

var express = require('express');
var app = express();

app.set("view engine","ejs"); // ejs를 사용하기 위해서 express의 view engine에 ejs를 set하는 코드입니다.

 

// 이 라인을 없으면, 앞 views 옵션은 기본으로 views 폴더(뒤)를 가르키지면, 명시적으로 적어주자.

// 뒤의 views 는 사용자 마음대로 바꿀 수 있다.

// views 는 res.render 에서 사용된다.

app.set("views", "views"); 


app.use(express.static(__dirname + '/public'));

// 2
app.get("/hello", function(req,res){ //  http://localhost:3030/hello 호출시
 res.render("hello", {name:req.query.nameQuery}); // render 에는 hello.ejs의 파일명부분과  파라미터를 넘겨준다.
}); 

// 3
app.get("/hello/:nameParam", function(req,res){  //  http://localhost:3030/hello/이름 호출시
 res.render("hello", {name:req.params.nameParam});  // render 에는 hello.ejs의 파일명부분과  파라미터를 넘겨준다.
});

app.listen(3000, function(){
console.log('Server On!');
});

 

 

> views/hello.ejs 에는 아래 내용 추가

2

<!-- views/hello.ejs -->

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Hello World!</title>
  <link rel="stylesheet" href="/css/master.css">
 </head>
 <body>
  <h1>Hello
   <% if(name){ %>
    <span class="name"><%= name %>!</span>
   <% } else { %>
    <span class="stranger">Stranger!</span>
   <% } %>
  </h1>
 </body>
</html>

 

> http://localhost:3000/hello 와 localhost:3000/hello/superman 으로 접속테스트 해보자.

 

[참조] https://www.a-mean-blog.com/ko/blog/Node-JS-%EC%B2%AB%EA%B1%B8%EC%9D%8C/Hello-World/HTTP-Methods-HTTP-Verbs-GET-POST-PUT-PATCH-DELETE

 

반응형

'Node.js' 카테고리의 다른 글

각종 설치 참조  (0) 2019.04.17
Atom 설치  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
내장 모듈  (0) 2018.10.31
Process 객체, exports 객체  (0) 2018.10.31

각종 설치 참조

Node.js
반응형

GIT : https://storycode.tistory.com/194

 

Atom : https://storycode.tistory.com/196

반응형

'Node.js' 카테고리의 다른 글

연습) Hello, World.  (0) 2019.04.17
Atom 설치  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
내장 모듈  (0) 2018.10.31
Process 객체, exports 객체  (0) 2018.10.31

Atom 설치

Node.js
반응형

1) https://atom.io설치

 

2) Atom Package 설치

File > Setting > Search packages 에서, 아래 패키지 각각 설치

 

highlight-selected

linter

linter-jshint

linter-csslint

file-icon-supplement

atom-runner

 

3) javasript 실행시 Alt + R

반응형

'Node.js' 카테고리의 다른 글

연습) Hello, World.  (0) 2019.04.17
각종 설치 참조  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
내장 모듈  (0) 2018.10.31
Process 객체, exports 객체  (0) 2018.10.31

설치 (Windows)

Node.js
반응형

1) https://nodejs.org에  > INSTALL

 

2) LTS 나 최신 버전 다운로드후 설치

 

3) Bash 에서 확인

$ node -v

$ npm -v

 

[참조] https://www.a-mean-blog.com/ko/blog/MEAN-Stack/%EA%B0%9C%EB%B0%9C-%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95/Node-JS-NPM-%EC%84%A4%EC%B9%98

반응형

'Node.js' 카테고리의 다른 글

각종 설치 참조  (0) 2019.04.17
Atom 설치  (0) 2019.04.17
내장 모듈  (0) 2018.10.31
Process 객체, exports 객체  (0) 2018.10.31
API  (0) 2018.10.31

내장 모듈

Node.js
반응형

[참조] http://cyberx.tistory.com/138?category=195624


1) 모듈 부르기

require()





2) os 모듈 부르기

var os = require('os')


   hostname() 운영체제의 호스트명을 반환합니다.
   type() 운영체제의 종류를 반환합니다.
   platfrom() 운영체제의 플랫폼을 반환합니다.
   arch() 운영체제의 아키텍처를 반환합니다.
   release() 운영체제의 버전을 반환합니다.
   uptime() 운영체제의 실행시간을 반환합니다.
   loadavg() 로드 에버리지 정보를 담은 배열을 반환합니다.
   totalmem() 시스템 총 메모리를 반환합니다.
   freemem 사용 가능한 메모리를 반환합니다.
   cpus CPU의 정보를 담은 객체를 반환합니다.
   getNetworkInterfaces() 네트워크 인터페이스의 정보를 담은 배열을 반환합니다.







3) url 모듈 부르기

// url 모듈 호출

var url = require('url');


// 구글에 nodejs라고 검색한 주소를 파싱

> var parsedURL = url.parse('https://www.google.co.kr/search?q=nodejs&oq=nodejs&aqs=chrome.0.69i59l3j69i60l3.968j0j8&sourceid=chrome&ie=UTF-8');

> parseURL






4) querystring 모듈 부르기

 // queryStrig 모듈 호출


var qs = require('querystring');

var objQuery = qs.parse(parsedURL.query);

var strQuery = qs.stringify(objQuery);


console.log(objQuery);

console.log(strQuery);






5) Util 모듈 부르기

utill.format() : 매개변수로 입력한 문자열을 조합해 반환합니다.

utill.debug() : 프로그램의 실행을 멈추고 입력값을 출력합니다.

utill.log() : timesteamp 시관과 함께 메시지를 출력한다.


외 다수


> var util= require('util');

> var data = util.format('%d%s %d%s',5, '월', 5, '일 어린이날')'

> console.log(data);




6) Crypto 모듈 부르기

// crypto모듈 호출

var crypto= require('crypto');


// 해시 생성

var shasum = crypto.createHash('sha1');

shasum.update('crypto_hash');

var output = shasum.digest('hex');

console.log(output)


var key = '비밀'; // 비밀키값

var input = 'password486'


//암호화

var cipher = crypto.createCipher('aes192', key);

cipher.update(input, 'utf8', 'base64');

var cipheredOutput = cipher.final('base64');


//암호화 해제

var decipher = crypto.createDecipher('aes192', key);

decipher.update(cipheredOutput,'base64', 'utf8');

var decipheredOutput = decipher.final('utf8');

     

console.log(input)                          // 출력값 : password486

console.log(cipheredOutput)            // 출력값 : 7OVfng/ujIZ8RkfxBIJAaA==

console.log(decipheredOutput )        // 출력값 : password486





7) File System 모듈 부르기

FileSystem을 줄여서 fs모듈이라 하는데요 파일 처리와 관련된 작업을 합니다. 

굉장히 많은 메소드가 있어 위에 링크따라 들어가셔러 언급되지 않은 메소드들도 함께 보면 좋을것 같습니다.



대부분의 메소드들이 동기/비동기로 나뉘어지는데,

동기방식을 사용하는 메소드에는 Sync라는 키워드가 붙어잇다고 보시면 좋을 것 같습니다.

비동기 방식은 callback함수를 마지막에 추가하시면 되는데

파일을 읽어오는 함수 readFile(비동기)/readFileSync(동기)로 설명하자면



동기방식은 (파일 경로, 인코딩)이라면

fs.readFileSync( 'test.txt' , 'utf8' );



비동기 방식은 마지막 인자에 callback 함수를 추가해주시면됩니다.

fs.readFile('test.txt', 'utf8'. function(error, data){ console.log(data); });


파일 처리를 하면서 중요한 부분 중 하나는 예외처리인데요 시스템이 비정상적으로 종료되지 않게 하기 위한 필수 사항입니다만

동기/비동기에 따라 예외처리하는 법이 다릅니다.

위에서 예상하실 수 있듯이, 비동기 방식에서는 callback함수에 예외처리가 가능합니다.

동기 방식에서는 try/catch 문으로 예외처리 하시면 됩니다.


그럼 예외처리까지해서 비동기 방식의 파일을 읽고 쓰기를 실행해보겠습니다.





비동기 방식 ---------------------

  // 모듈을 호출합니다.

  var fs = require('fs');


  // 파일 쓰기

  fs.writeFile( 'test.txt' , 'testing~' , 'utf8', function (error) {

   if(error){

       console.log(error);

   }else{

        console.log('파일 작성 완료');

   }

  });


  // 파일 읽기

  fs.readFile( 'test.txt' , 'utf8' , function (error, data){ 

   if(error){

       console.log(error);

   }else{

        console.log(data);

   }

  });

  

  


동기방식 -------------------------

크게 다를거 없이 callback함수를 지우시고 전체를 try문으로 감싼 후 catch문에 error가 발생했을 경우의 처리 방식을  작성하시면 됩니다.



try{

    fs.writeFileSync('test.txt', 'hello summer', 'utf8');

}catch(e){

    console.log(e);

}







이 외에도 

파일에 내용을 추가하는 appendFile/appendFileSync

파일이 존재하는지 확인하는 exists

파일의 이름을 재정의 하는 rename/renameSync 등등

다양한 메소드들을 제공

반응형

'Node.js' 카테고리의 다른 글

Atom 설치  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
Process 객체, exports 객체  (0) 2018.10.31
API  (0) 2018.10.31
설치  (0) 2018.10.31

Process 객체, exports 객체

Node.js
반응형

Global 객체, 전역변수, 전역 객체


1) Process 객체

> process.version

'v6.14.3'


process.argv

[ '/usr/bin/node' ]


process.exit()

[root@localhost ~]#


> process.memoryUsage()

{ rss: 19496960,

  heapTotal: 8421376,

  heapUsed: 4241024,

  external: 9036 }


> process.uptime()
25.124


2) exports

# vi sub.js


exports.multiple = function (a,b)

{

        return a*b;

};



> var module=require('./sub.js');

undefined

> console.log(module.multiple(2,3));

6


[참조] http://cyberx.tistory.com/135

반응형

'Node.js' 카테고리의 다른 글

Atom 설치  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
내장 모듈  (0) 2018.10.31
API  (0) 2018.10.31
설치  (0) 2018.10.31

API

Node.js
반응형

https://nodejs.org/dist/latest-v6.x/docs/api/


https://nodejs.org/docs/latest/api/index.html

반응형

'Node.js' 카테고리의 다른 글

Atom 설치  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
내장 모듈  (0) 2018.10.31
Process 객체, exports 객체  (0) 2018.10.31
설치  (0) 2018.10.31

설치

Node.js
반응형

1. 환경

Centos 7


2. 설치

[참조] http://kwangsics.tistory.com/entry/CentOs7-nodeJs-%EC%84%A4%EC%B9%98

yum list epel-release

yum install epel-release

yum repolist

yum install npm nodejs

node -v
npm -v

3. node console 실행

# node

> console.log('hello')

hello

undefined



반응형

'Node.js' 카테고리의 다른 글

Atom 설치  (0) 2019.04.17
설치 (Windows)  (0) 2019.04.16
내장 모듈  (0) 2018.10.31
Process 객체, exports 객체  (0) 2018.10.31
API  (0) 2018.10.31