Develoraptor Blog

Login

Resource mangement with JS generators

In Javascript, if you break from a for ... of loop, the iterator's return function will always be called. Since this calls any relevant finally block in a generator, you can use generators and loops to handle resource tidy up:

function* readFile(filename){
  const fileHandle = fs.open(filename);
  try {
    yield fileHandle;
  } finally {
    fs.close(fileHandle);
  }
}

for(const fileHandle of readFile('myFile.txt')){
  if(today === 'Sunday') {
    console.log('Sorry, today is my rest day.');
    break;
  }
  fileHandle.write('Hello!');
}