title: Node.js File Upload Memory Leak
body: <p>I am creating an API with Node.js and Express. When a user uploads a file, the server alters it with the <code>sharp</code> image processing library and then uploads it to a Google Cloud Storage bucket. The RAM usage of the node process increases by the size of the uploaded file and never decreases, even when running manual garbage collection. When there is no RAM left to allocate, the server crashes.</p>
  
  <p>Here is a reproduction of the problem:</p>
  
  <p>index.js</p>
  
  <pre><code>const express = require('express')
  const GCS = require('@google-cloud/storage')
  const Multer = require('multer')
  const sharp = require('sharp')
  
  const upload = Multer({ storage: Multer.MemoryStorage, })
  
  const storage = new GCS({
      projectId: 'myProject',
      keyFilename: './key.json'
  }).bucket('myBucket')
  
  
  const app = express();
  
  app.get("/", (req, res) =&gt; {
      res.sendFile(__dirname + '/index.html')
  })
  
  app.post("/upload", upload.single('media'), (req, res) =&gt; {
      console.log(req.file)
      sharp(req.file.buffer).rotate().resize(1920, 1920).toBuffer().then(b =&gt; {
          const fileUpload = storage.file('test/' + Date.now())
  
          const fileStream = fileUpload.createWriteStream({
              metadata: {
                  contentType: req.file.mimetype
              },
              resumable: false
          });
  
          fileStream.on('error', (err) =&gt; {
              console.log(err)
              res.send("Server Error")
          });
  
          fileStream.on('finish', () =&gt; {
              fileUpload.makePublic().then(() =&gt; {
                  res.send("DONE")
              })
          })
          fileStream.end(b)
      }).catch(e =&gt; {
          console.log(e)
          res.send("Server Error")
      })
  })
  
  app.listen(3000, () =&gt; {
      console.log("Server is running...")
  })
  </code></pre>
  
  <p>index.html</p>
  
  <pre><code>&lt;form action="/upload" enctype="multipart/form-data" method="POST"&gt;
      &lt;input type="file" name="media"&gt;
      &lt;input type="submit"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>I also performed a test using Multer.DiskStorage, and the RAM usage stayed consistent and did not increase nearly as much. This method, however, is not preferable because of disk storage, directory permissions, etc.</p>
  
  <p>I appreciate any help you may have to offer!</p>