programming/node.js

[Node.js] Node.js w3schools Tutorial - Day.2

LeeBorn 2019. 11. 18. 00:00
반응형

node.js

*해당 내용은 https://www.w3schools.com/nodejs/ 의 튜토리얼을 따라 하며 정리하는 글입니다.

[Day1]

내장 모듈들

노드에는 내장된 모듈이 몇 개 있다.

그중 HTTP 모듈도 있는데, 사용하려면 require() 메소드를 사용하면 된다.

var http = require('http');

url 모듈

1
2
3
4
5
6
7
8
9
var http = require('http');
var url = require('url');
 
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type''text/html'});
  var q = url.parse(req.url, true).query;
  var txt = q.year + " " + q.month;
  res.end(txt);
}).listen(8080);

 

내장 모듈중엔 url 모듈도 있다.

내장 모듈이라 마찬가지로 require() 메소드를 통해 사용할 수 있다.

http://localhost:8080/?year=2017&month=July

위의 URL로 서버를 접속했을 때, 6번째 줄에서 query object로 반환해준다.

그래서 q.year는 2017이 출력되고, q.month는 July가 출력된다.

 

url 모듈 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
 
console.log(q.host);      //returns 'localhost:8080'
console.log(q.pathname);  //returns '/default.htm'
console.log(q.search);    //returns '?year=2017&month=february'
 
var qdata = q.query;      //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'
 
///////////////////////////////////////////////
console.log(q);
console.log(qdata);
 

url.parse()를 통해 전체적으로 아래와 같은 반환 값을 가진다.

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'localhost:8080',
  port: '8080',
  hostname: 'localhost',
  hash: null,
  search: '?year=2017&month=february',
  query: [Object: null prototype] { year: '2017', month: 'february' },
  pathname: '/default.htm',
  path: '/default.htm?year=2017&month=february',
  href: 'http://localhost:8080/default.htm?year=2017&month=february' 
}

 

File System

var fs = require('fs');

파일은 readFile(), appendFile(), open(), writeFile() 등의 메소드를 사용할 수 있다.

 

Upload Files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
 
http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.uploadDir = "D:/tmp";            // err Error: EXDEV: cross-device link not permitted : 임시 폴더를 변경 하기 같은 파티션으로
    
    form.parse(req, function (err, fields, files) {
          var oldpath = files.filetoupload.path;
          var newpath = 'D:/USER_PATH/uploadFiles/' + files.filetoupload.name;
          
          fs.rename(oldpath, newpath, function (err) {
            if (err) throw err;
            res.write('File uploaded and moved!');
            res.end();
          });
    });
  } else {
    console.log("form create");
    res.writeHead(200, {'Content-Type''text/html;charset=utf-8'});    // 한글파일 이름 제대로 출력되게 charset=utf-8 추가
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);
 

파일을 폼으로 올리고, 파일을 원하는 위치로 이동시키는 예제다.

원래 예제에서 변경된 부분이 2가지가 있다.

22번 줄에서 한글 파일 이름을 제대로 출력하기 위해서 "charset=utf-8"을 추가해 주었다.

파일을 D드라이브로 옮기고 싶어서, 임시파일 저장소도 D로 변경했다.

8번째 줄을 실행시키지 않는다면, C에서 D로 이동하게 되는데,

이때 'err Error: EXDEV: cross-device link not permitted'  에러가 뜰 것이다.

반응형