Memory Management in Node.js

The Apryse SDK in Node.js automatically cleans up all objects in memory when a process is initialized using PDFNet.runWithCleanup() once the process has finished running. In almost all cases, it is recommended to use the PDFNet.runWithCleanup() function to avoid memory leaks and complicated memory management.

For most situations, using PDFNet.runWithCleanup() and [Obj].takeOwnership() is sufficient for managing memory. However, there are additional ways to manage your memory usage:

Retain objects

In some situations you may wish to retain an object after the process has finished. A common example of this would be to create a document and retain it after processing. The ElementEdit sample on the samples page has an example of how this can be done.

  • [Obj].takeOwnership()

Deallocate objects

Deallocates individual objects. Only objects that derive from PDFNet.Destroyable have this method.

  • [Obj].destroy()

Deallocate stack

Stack-based deallocation. Calling endDeallocateStack() will deallocate all objects that were created since the last call to PDFNet.startDeallocateStack(). In general, stack-based deallocation is recommended because it is easier to manage for larger sections of code.

  • PDFNet.startDeallocateStack()
  • PDFNet.endDeallocateStack()

Some examples

Here are some examples for the various deallocation options

Automatic (default) deallocation

JavaScript

1async function main() {
2 try {
3 // documents require deallocation
4 const doc = await PDFNet.PDFDoc.create();
5 // object that requires deallocation
6 const page_iter = await doc.getPageIterator();
7 // object that requires deallocation
8 const writer = await PDFNet.ElementWriter.create();
9 } catch (err){
10 console.log(err);
11 }
12}
13
14// deallocates all objects once main finishes running
15PDFNet.runWithCleanup(main);

Individual deallocation

JavaScript

1async function main() {
2 try {
3 const doc = await PDFNet.PDFDoc.create();
4 const page_iter = await doc.getPageIterator();
5 const writer = await PDFNet.ElementWriter.create();
6 } catch (err){
7 console.log(err);
8 } finally {
9 await doc.destroy();
10 await page_iter.destroy();
11 await writer.destroy();
12 }
13}
14PDFNet.runWithoutCleanup(main);

Stack-based deallocation

JavaScript

1async function main() {
2 try {
3 await PDFNet.startDeallocateStack();
4 const doc = await PDFNet.PDFDoc.create();
5 const page_iter = await doc.getPageIterator();
6 const writer = await PDFNet.ElementWriter.create();
7 await PDFNet.endDeallocateStack();
8 } catch (err){
9 console.log(err);
10 }
11}
12PDFNet.runWithoutCleanup(main);

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales