#741·nsfwjs

[Node.JS] Memory leak - Server reaches 100% memory after 5 or 6 days

Author: MadriixCreated Apr 28, 2023Updated May 18, 2026

Hi

With the http server below, my server with 32 GB of memory almost reaches 100% of memory used after 4 to 6 days, do you know where the problem could come from?

In the browser just type this: http://x.x.x.x:3000/?url=https://test.domain.com/images.jpg

const http = require('http');
const https = require('https');
const tf = require('@tensorflow/tfjs-node');
const nsfw = require('nsfwjs');
const url1 = require('url');

const server = http.createServer(async (req, res) => {

  const parsedUrl = url1.parse(req.url, true);
  const urlValue = parsedUrl.query.url;

  console.log(urlValue);

  if (typeof urlValue !== "undefined") {
    try {
      const url = new URL(urlValue);
      const client = (url.protocol == "https:") ? https : (url.protocol == "http:") ? http : http;

      const requestTimeout = setTimeout(() => {
        res.writeHead(408, {'Content-Type': 'text/plain'});
        res.end('Request Timeout');
      }, 5000); // Set a timeout of 5 seconds for the request

      const response = await new Promise((resolve, reject) => {
        client.get(url, resolve).on('error', reject);
      });

      const chunks = [];
      response.on('data', (chunk) => chunks.push(chunk));

      await new Promise((resolve, reject) => {
        response.on('end', resolve).on('error', reject);
      });

      clearTimeout(requestTimeout); // Clear the timeout if the request completes before the timeout is reached
      const buffer = Buffer.concat(chunks);
      const model = await nsfw.load(); // To load a local model, nsfw.load('file://./path/to/model/')
      // Image must be in tf.tensor3d format
      // you can convert image to tf.tensor3d with tf.node.decodeImage(Uint8Array,channels)
      const image = await tf.node.decodeImage(buffer, 3);
      const predictions = await model.classify(image);
      image.dispose(); // Tensor memory must be managed explicitly (it is not sufficient to let a tf.Tensor go out of scope for its memory to be released).
      console.log(predictions);
      res.writeHead(200, {
        'Content-Type': 'application/json'
      });
      res.end(JSON.stringify(predictions));
    } catch(e) {
      console.error(e);
      res.writeHead(400, {'Content-Type': 'text/plain'});
      res.end('Bad Request : '+e);
    }
  } else {
    res.writeHead(400, {'Content-Type': 'text/plain'});
    res.end('Bad Request (2)');
  }

});


server.listen(3000, () => {
  console.log('The server is listening on port 3000...');
});

It's a pity that there is a memory leak because the detection works well