반응형


파일 Open , close  이벤트 처리


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
31
32
33
34
35
36
37
38
39
40
var fs = require('fs');
 
//파일이  없으면 만든다
fs.open('./output1.txt''w',
 
    function (err, fd)          //파일 열기 완료후 call - back
    {
        if (err) {
            console.log('파일 open 에러');
            console.dir(err);
            return;
        }
 
        //파일이 열린 이후, 팡리에다가 쓰기
        //쓸 내용을 변수로 따로 만듬
 
        //Buffer 문자열을 담아두는 객체, 길이등을 얻어올 수 있음 또는 다른 문자열과 인코딩방식을 지정해 Buffer 에 쓸 수 있음
        var buf = new Buffer('안녕\n!!!');
        fs.write(fd, buf, 0, buf.length,            //어디서부터 쓸 것인지 버퍼의 시작점과 끝점 지정
            function (err, written, buffer)         //쓰기가 완료 된 이후 실행되는 call - back
            {
                if (err) {
                    console.log('파일 쓰기 에러');
                    console.dir(err);
                    return;
                }
                console.log('쓰기 완료');
 
 
                fs.close(fd, function ()            //닫기가 완료된 이후의 call - back
                {
                    console.log('파일 닫기 완료');
                }
                );
 
            }
        );
 
 
    });




결과  :

쓰기 완료

파일 닫기 완료



output1.txt : 

안녕

!!!







스트림으로 읽어들이는 방식


위 output1.txt 파일에 써진 내용을 읽어들인다


파일을 읽는 중간 중간 data 이벤트가 발생하는데 읽은 파일이 짧던 크던 이 이벤트는 초반 처음에 한번 호출되고 

파일이 짧아 로딩 시간이 짧아지게 되면 data 이벤트는 반복하여 호출되지 않는다, 일정 크기 이상이어 중간에 한번씩 호출된다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var fs = require('fs');
var infile = fs.createReadStream('./output1.txt', { flags: 'r' });
 
//스트림으로 읽어들이는 과정 도는 읽기가 완료 됐을때 이벤트가 발생된다
 
 
// 중간 중간 읽어 들이는 중간 이벤트
infile.on('data'function (data) {
    console.log('읽어들인 데이터 : ' + data);
});
 
//읽기가 완료 됐을때의 이벤트
infile.on('end'function () {
    console.log('읽기 종료');
});


결과화면 : 





반응형
반응형
쓰기와 마찬가지로 동기 비동기가 있다


비동기 파일 쓰기 처리
 /**
     * Asynchronously writes data to a file, replacing the file if it already exists.
     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
     * URL support is _experimental_.
     * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
     * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
     */
    export function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void;




동기식 파일 쓰기 처리
/**
     * Synchronously writes data to a file, replacing the file if it already exists.
     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
     * URL support is _experimental_.
     * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
     * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
     * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
     * If `encoding` is not supplied, the default of `'utf8'` is used.
     * If `mode` is not supplied, the default of `0o666` is used.
     * If `mode` is a string, it is parsed as an octal integer.
     * If `flag` is not supplied, the default of `'w'` is used.
     */
    export function writeFileSync(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void;







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var fs = require('fs');
 
 
//동기 파일 쓰기
//fs.writeFileSync
 
//비동기 파일 쓰기, 
fs.writeFile('./output.txt''hello.'function (err) {
    if (err) {
        console.log('에러발생');
        console.dir(err);
        return;
    }
    console.log('파일쓰기완료'); 
   }
);
console.log('파일 쓰기 명령');
   




결과 : 


비동기 기준임으로 파일 스기 명령이 먼저 찍힌 것을 볼 수 있다





써진 내용




반응형
반응형
nodejs 파일 읽기 방식 : 

readFileSync: 동기
readFile :비동기


package.json 파일

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
  "name""nodejs-console-app1",
  "version""0.0.0",
  "description""NodejsConsoleApp1",
  "main""app.js",
  "author""PC_D",
  "dependencies"{
    "nconf""^0.10.0",
    "underscore""^1.8.3"
  },
  "devDependencies"{},
  "scripts"{
    "test""echo \"Error: no test specified\" && exit 1"
  },
  "license""ISC"
}
 






파일 읽기 example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var fs = require('fs');
 
/*
 * //파일을 다 읽은 이후에 완료가 뜬다
var data = fs.readFileSync('./package.json', 'utf8');
console.log(data);
console.log('완료');
*/
 
//비동기 방식으로
//파일을 읽는 동안 완료가 먼저 뜨고 그다음 파일 내용을 보여준다
//파일이 다 읽히면 call back 함수를 호출한다
var data = fs.readFile('./package.json''utf8'function (err, data) {
    //파일 다 읽었을 대 호출 됨
    console.log(data);
});
console.log('완료');
 
 





결과 :


이며 결과는 동기 일때 '완료'가 파일 내용 하단에 뜬다



반응형
반응형

기존 전역 객체 process 가 아닌 모듈로 만들어 이벤트를 호출 할 수있는 즉 객체에 EventEmitter를

상속 받아 이벤트를 호출하는 구조


util 모듈을 통해 상속구문을 보다 간편하게 처리할 수 있다


//calculation는 EventEmitter을 상속 받는다
util.inherits(calculation, EventEmitter);



'stop' 인 사용자 정의형 이벤트를 calculation 에 등록함


calculation.js

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
 
 
var EventEmitter = require('events').EventEmitter;      //이벤트를 위한 모듈
var util = require('util');                             //프로포타입 객체를 쉽게 상속 할 수 있게 해줌
 
 
var calculation = function () {
 
    this.on('stop'function ()
        {
        console.log('calculation 에 stop 이벤트 전달됨');
        }
    );
 
};
 
calculation.prototype.add = function (a, b) {
    return a + b;
}
 
//calculation는 EventEmitter을 상속 받는다
util.inherits(calculation, EventEmitter);
 
 
 
module.exports = calculation;
 
 




1
2
3
4
5
6
7
var calc = require('./calculation');
 
//모듈로 읽어온 것을 객체로 만들 수 있음 moudle.exports 느 calculation 과 동일한 형태임으로
var calculationReal = new calc();
 
calculationReal.emit('stop');
 





결과




반응형
반응형

emit 으로 해당 이벤트를 보내고
on 을 통해 등록된 이벤트가 실행된다

이벤트는 EventEmitter 를 상속 받아 객체를 만들어 이벤트를 처리한다

require();

process 전역 객체는 이미 EventEmitter 를 상속 받고 있기때문에 on() 함수를 쓸 수 있음

exit 이벤트가 발생되면 함수가 실행됨

process 에 {'exit', function(){ ...} } 를 등록한것

이벤트 중에는 미리 정의되어 있는 것들이 있음 (ex : exit)


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
31
32
 
//미리 정의된 이벤트
process.on('exit', function(){
    console.log('exit 이벤트 발생 되었음');
});
 
 
//사용자 정의형 이벤트
process.on('tick', function (num) {
    console.log('tick 이벤트 실행** : ' + num);
}
);
 
console.log('2초후 이벤트 실행 대기');
 
setTimeout(
    function () {
 
        process.emit('tick', 20000);
    }
    , 2000
);
 
 
setTimeout(
    function () {
        process.exit();     //이벤트 발생
    }
    , 2000
);
 
 
   

         



결과 화면

2호후 이벤트 대기 실행 부분에서 멈춰 있다가 2호 후에 이벤트 들이 실행된다





반응형
반응형


'url' 과 'querystring' 모듈로 주소 파싱하기


검색했던 query 찾는 방법


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
var url = require('url');
 
 
//naver 에서 3dmp 검색한 url
var urlStr = 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=3dmp';
 
 
var curUrl = url.parse(urlStr); //각 url 을 각 속성으로 분리
 
console.dir(curUrl);
 
console.log();
 
 
console.log(curUrl.query);
 
console.log(url.format(curUrl));   // 다시 합치기
 
 
console.log();
 
var querystring = require('querystring');       //query 만을 알아보곳 피을떄 querystring 모듈 로딩
console.log(querystring.parse(curUrl.query));
 
console.log();
 
console.log(querystring.parse(curUrl.query).query);  // parse 한다음 분리된 속성 중  query 를통해 얻을 수 있음
 
console.log();




반응형
반응형
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
//url 모듈 불러오기
 
var url = require('url');
 
 
 
//이런 주소를 url 모듈을 사용하면 분해할 수 있음
 
var curUrl = url.parse('https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=NodejsTest');
 
 
 
//protocal : https,  host : www.naver.com, query : ? 이후의 것 
 
 
 
//이때 curUrl 은 객체로 아래 결과와 같은 멤버들을 가지고 있다
console.dir(curUrl);
 
 

 
 
//이 객체를 다시 문자열로 합칠려면 
 
var oriUrl =  url.foramt(curUrl); 을 사용하면 된다
 
 

cs





결과 

Url {

  protocol: 'https:',

  slashes: true,

  auth: null,

  host: 'search.naver.com',

  port: null,

  hostname: 'search.naver.com',

  hash: null,

  search: '?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=NodejsTest',

  query: 'where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=NodejsTest',

  pathname: '/search.naver',

  path: '/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=NodejsTest',

  href: 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=NodejsTest' }




이때 

require('querystring'); 모듈을 로딩하고

querysting.parse(curUrl.query); 를 하게 도면 NodejsTest 만 얻을 수 도 있다






반응형

+ Recent posts