Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

Node.js의 스트림 writable.cork() 및 uncork() 메서드

<시간/>

writable.cork() 메서드는 기록된 모든 데이터가 메모리 내부에 버퍼링되도록 강제하는 데 사용됩니다. 이 버퍼링된 데이터는 stream.uncork() 또는 stream.end() 메서드가 호출된 후에만 버퍼 메모리에서 제거됩니다.

구문

코르크()

writeable.cork()

풀기()

writeable.uncork()

매개변수

작성된 데이터를 버퍼링하기 때문입니다. 필요한 매개변수만 쓰기 가능한 데이터가 됩니다.

예시

이름이 cork.js인 파일을 만들고 아래 코드 스니펫을 복사합니다. 파일을 생성한 후 다음 명령을 사용하여 아래 예와 같이 이 코드를 실행하십시오 -

node cork.js

cork.js

// Program to demonstrate writable.cork() method
const stream = require('stream');

// Creating a data stream with writable
const writable = new stream.Writable({
   // Writing the data from stream
   write: function(chunk, encoding, next) {
      // Converting the data chunk to be displayed
      console.log(chunk.toString());
      next();
   }
});

// Writing data
writable.write('Hi - This data is printed');

// Calling the cork() function
writable.cork();

// Again writing some data
writable.write('Welcome to TutorialsPoint !');
writable.write('SIMPLY LEARNING ');
writable.write('This data will be corked in the memory');

출력

C:\home\node>> node cork.js
Hi - This data is printed

cork() 메서드 사이에 쓰여진 데이터만 인쇄되고 나머지 데이터는 버퍼 메모리에 코르크됩니다. 아래 예는 버퍼 메모리에서 위 데이터의 코르크를 푸는 방법을 보여줍니다.

예시

uncork() - uncork.js

방법에 대한 예를 하나 더 살펴보겠습니다.
// Program to demonstrate writable.cork() method
const stream = require('stream');

// Creating a data stream with writable
const writable = new stream.Writable({
   // Writing the data from stream
   write: function(chunk, encoding, next) {
      // Converting the data chunk to be displayed
      console.log(chunk.toString());
      next();
   }
});

// Writing data
writable.write('Hi - This data is printed');

// Calling the cork() function
writable.cork();

// Again writing some data
writable.write('Welcome to TutorialsPoint !');
writable.write('SIMPLY LEARNING ');
writable.write('This data will be corked in the memory');

// Flushing the data from buffered memory
writable.uncork()

출력

C:\home\node>> node uncork.js
Hi - This data is printed
Welcome to TutorialsPoint !
SIMPLY LEARNING
This data will be corked in the memory

버퍼링된 메모리가 uncork() 메서드를 사용하여 플러시되면 위 예제의 전체 데이터가 표시됩니다.