简体   繁体   English

Node.js 应用程序在生产中启动永无止境的流程

[英]Node.js application starts never ending processes in production

I am hosting a node.js application on cPanel.我在 cPanel 上托管了一个 node.js 应用程序。 It is nothing but simple RESTful web APIs using express which include CRUD.它只不过是使用包含 CRUD 的 express 的简单 RESTful web API。 The issue that I am facing is that the number of processes are getting increased by time, means some of the previous processes are never ending and application keeps on adding until the point where my server reaches resource limit and all the applications stop working.我面临的问题是进程的数量随着时间的推移而增加,这意味着以前的一些进程永无止境,应用程序不断添加,直到我的服务器达到资源限制并且所有应用程序停止工作。

cPanel actually doesn't have a way to console.log() any errors which I am writing the code to do from inside my application. cPanel 实际上没有办法console.log()任何我正在编写代码要从我的应用程序内部执行的错误。 All I can see is the main domain from where the processes are stemming.我所能看到的只是流程产生的主要领域。

I tried to write my own log file for that but that didn't help too我试图为此编写自己的日志文件,但这也无济于事

I am writing this in my terminal to check processes ps -ef | grep node我在我的终端上写这个来检查进程ps -ef | grep node ps -ef | grep node (because I know all the processes are only node.js processes). ps -ef | grep node (因为我知道所有进程都只是 node.js 进程)。 I noticed that the number of processes I can see in this command are different (way less) than that I can see in side my cPanel dashboard!我注意到我可以在此命令中看到的进程数量与我在 cPanel 仪表板中看到的不同(少得多)!

UPDATE:更新:

For an example, this is one of the APIs which is creating issue:例如,这是创建问题的 API 之一:

My app.js (entry point) :我的app.js (入口点)

require("dotenv").config();
const fs = require("fs");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const cors = require("cors");

const mongoose = require("mongoose");

// Initialize the app
const app = express();

// Enable CORS
app.use(cors({ origin: true }));
 
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
 
// setup the logger
app.use(morgan('combined', { stream: accessLogStream }))

// Parse the body to JSON
app.use(bodyParser.json());

// Serving static files
app.use("/images", express.static("images"));

// Routes middlewares go here!
app.use("/api/categories", require("./routes/category-routes"));
app.use("/api/users", require("./routes/user-routes"));
app.use("/api/sellers", require("./routes/seller-routes"));
app.use("/api/services", require("./routes/service-routes"));
app.use("/api/resellers", require("./routes/reseller-routes"));
app.use("/api/support", require("./routes/support-routes"));
app.use("/api/trackings", require("./routes/tracking-routes"));

app.use((err, req, res, next) => {
  console.log(err);
  res
    .status(500)
    .send({ success: false, error: err, errors: ["Something went wrong"] });
});

// Start listening finally
const port = process.env.PORT || 5000;

mongoose
  .connect(process.env.MONGO_URI, {
    // .connect(process.env.MONGO_URI_NAI_NAI_NAI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
  })
  .then(() => {
    app.listen(() => {
      console.log(`Server started on port ${port}`);
    });
  })
  .catch((err) => {
    try {
      fs.appendFileSync("my-own-log-file.txt", `\n\n${err}`);
    } catch (err) {
      console.log(err);
    }
    process.exit(1)
    console.log(err);
  });

Here I am registring the route:我在这里注册路线:

// @route   POST /api/services/filtered-by-state
// @desc    To fetch all services filtered by state
// @access  public

router.post(
  "/filtered-by-state/",
  body("state")
    .trim()
    .not()
    .isEmpty()
    .withMessage("Please enter choose a state"),
  checkValidity,
  serviceControllers.getServicesFilteredByState
);

This is the controller:这是 controller:

exports.getServicesFilteredByState = (req, res) => {
  let page = req.query.page || 1;
  const { state, sellerId } = req.body;
  let options = {};

  if (page) {
    page = parseInt(page);
  }

  if (state === "Australia Wide") {
    options = { state }; // Look for only documents where state is 'Australia wide'
  } else {
    // Look for documents where state is 'Australia wide' or ```state``` itself
    options = { state: { $in: ["Australia Wide", state] } };
  }

  if (!sellerId) {
    options.isHidden = false;
  }

  let totalItems = 0;

  Service.find(options)
    .countDocuments()
    .then((numServices) => {
      totalItems = numServices;
      return Service.find(options)
        .sort("sortingOrder")
        .populate("sellerId")
        .populate("categoryId");
      // .skip((page - 1) * ITEMS_PER_PAGE)
      // .limit(ITEMS_PER_PAGE);
    })
    .then((foundServices) => {
      res.status(200).json({
        success: true,
        totalItems,
        services: foundServices,
      });
    })
    .catch((err) => {
      console.log(err);
      res.status(500).status("Something went wrong");
    });
};

This is simple CRUD!这是简单的 CRUD!

A Node.js application runs on single thread and the event loop also runs on the same thread. Node.js 应用程序在单线程上运行,并且事件循环也在同一线程上运行。 So we can say that Node.js is single-threaded but the catch is that there are some libraries in Node.js that are not single-threaded.所以我们可以说 Node.js 是单线程的,但问题是 Node.js 中有一些库不是单线程的。

Node.js internally uses the libuv library which is responsible for handling operating system related tasks, like asynchronous I/O based operation systems, networking, concurrency, etc. Libuv sets up a thread pool of x threads to perform OS-related operations by utilizing the power of all the CPU cores. Node.js 内部使用libuv库,负责处理操作系统相关的任务,如基于异步 I/O 的操作系统、网络、并发等。的所有 CPU 内核。 For example, if you have a computer with 4 CPU cores, Libuv will create a thread pool of 4 threads, each thread from the pool is assigned to every core.例如,如果您有一台具有 4 个 CPU 内核的计算机,Libuv 将创建一个由 4 个线程组成的线程池,池中的每个线程都分配给每个内核。 This results in one thread per core.这导致每个内核一个线程。

However, you can change this value by changing the UV_THREADPOOL_SIZE environment variable:但是,您可以通过更改 UV_THREADPOOL_SIZE 环境变量来更改此值:

process.env.UV_THREADPOOL_SIZE = numOfThreads;

In case you are not doing anything wierd with your code, this is totally normal for Node.js and will use as many CPU cores as available to perform better.如果你没有对你的代码做任何奇怪的事情,这对于 Node.js 来说是完全正常的,并且会使用尽可能多的 CPU 内核来获得更好的性能。

I have found a really interesting article that explains everything in detail: Is Node.js Really Single-Threaded?我发现了一篇非常有趣的文章,它详细解释了所有内容: Node.js 真的是单线程的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM