javascript – Node.js programmatic PM2 – list processes

var pm2 = require('pm2')

pm2.connect(function(err) {
  if (err) {

    name: "proc1",
    script: __filename,
  }, (err, apps) => {
    if (err) { throw err }
    name: "proc2",
    script: __filename,
  }, (err, apps) => {
    if (err) { throw err }

  // Get all processes running
  pm2.list(function(err, procList) {

node.js – How to redirect page after using the DELETE method in express?

I’m a newbie in Nodejs and I’m coding a to-do app as a practical exercise. I’m having a problem that I cannot return to my index page “/” after using the DELETE method in Express. I use the deleteMany() of Mongoose to delete my docs, however after deleted all of those docs I couldn’t return to the “/” page, the system threw an error in the console:

DELETE http://localhost:3000/ 404 (Not Found)

although using res.redirect("/") is fine with POST method. I’ve found a guy with the same problem as mine on Stack Overflow, but his solutions are not working in my app. Another solution of him is using pure Javascript to redirect from the client, however I want to do this job in the severside.

app.delete("/delete/:item", function(req,res) {
    var item = req.params.item;
    //Using regex to change the url task to its original name
    var delTask = item.replace(/-/g," ");

    db.task.deleteMany({"name": delTask}, (err) => {
        if (err) throw err;
        console.log("Removal successful");

javascript – Code refactoring for services and controller based architecture node.js

I have my app structured as below,

Routes -> Controllers -> Services

So, for /bookings there is BookingController and BookingService

Role of controller is to take the request and distribute the tasks between one or more services.

Now Let’s have a look on below code.


const {
} = require('config');

const models = require('../models');
const NewOrderService = require('./NewOrderService');
const AuthService = require('./AuthService');
const TaxAndDiscountService = require('./TaxAndDiscountCalculationService');
const CartService = require('./CartService');
const RequestService = require('./RequestService');
const LocationService = require('./LocationService');

module.exports = async (users) => {
  const promises = => models.sequelize.transaction(async (t) => {
    let userId;
    let cartValue;
    const notes = {};
    const existingUser = await AuthService.isUserExist({ mobile: });
    if (!existingUser) {
      const loginData = await models.Login.create({
        is_blocked: false,
        username: user.customer_name,
        user_role_id: Customer,
        user_type_id: CustomerB2c,
      }, { transaction: t });
      const userData = await models.UserDetail.create({
        Wallet: {
          coin_balance: 0,
        first_name: user.customer_name,
        city_id: user.city_id,
      }, {
        include: (models.Wallet),
      }, { transaction: t });
      userId =;
    } else {
      userId = existingUser.user_id;
    const locations = await LocationService.doGetSuggestedLocations({
      currentLng: user.lng,

    const address = await models.UserAddress.create({
      user_id: userId,
      location_id: locations(0).id,
    }, { transaction: t });
    const vehicle = await models.UserVehicle.create({
      is_default: true,
      user_id: userId,
      vehicle_id: user.master_vehicle_id,
      registration_number: user.reg_num,
    const { cartId } = CartService.getUserCart({ userId });
      itemId: user.item_id,
      itemQuantity: 1,
    const cartItems = await NewOrderService.doGetCartItemsByUserId(userId);
    if (user.coupon_code) {
      const userCartValue = await NewOrderService.doApplyCoupon({
        zoneId: locations(0).zoneId,
        slotId: user.slot_id,
        couponCode: user.coupon_code,
      cartValue = userCartValue;
      notes.couponCode = user.coupon_code;
      notes.couponDiscount = cartValue.coupon_discount;
    } else {
      cartValue = TaxAndDiscountService.calculateCartValue(cartItems);
    const item = await models.Item.findOne({
      where: {
        item_id: user.item_id,
      include: {
        model: models.Service,
        attributes: ('id'),
      attributes: ('id'),
    const services = ({
      slot_id: user.slot_id,
      booking_date: user.booking_date,
    const order = await NewOrderService.doCreateBookingOrder({
      transaction: t,
    const bookings = await RequestService.doCreateServiceRequest({
      transaction: t,
      requestedServices: services,
    order.bookings = bookings;
      bookingId: order.bookings(0).id,
    return order;
  return Promise.all(promises);

The code creates users in bulk also creates their wallet, vehicle, address and finally order.

A lot of things are going on here.

I come always in situation like this, and I get frustrated and feel so bad about the code. I have no idea how to refactor it.

But, I do have some thoughts:

Create separate functions like bulkCreateUserWithWallet, createUserVehicle and createUserAddress and so on, and use these functions instead.

But still those functions would only for one time use, I don’t need them anywhere else, because here they might need fewer arguments and some other places I need to insert more data in table address field.

Also, they should be in a single transaction.

I also thought using repository pattern, so between services and models I would have another layer called Repository.

But I don’t know how to implement this using sequelize.

I am also familiar with patterns like higher order functions and pure functions. Can I use it them here somehow?

Finally a request, Please don’t close it! I am ready to bear downvotes no issues.

I don’t know where else to ask this question.

node.js – Fazer deploy no heroku

Estou tentando fazer um deploy de um aplicação no heroku de uma aplicação NodeJS 14.5.1

Toda vez que faço os seguintos comandos

git add .

git commit heroku

git push heroku master

Tenho o seguinte log

-----> Build failed
       We're sorry this build is failing! You can troubleshoot common issues here:
       Some possible problems:
       - A module may be missing from 'dependencies' in package.json
 !     Push rejected, failed to compile Node.js app.
 !     Push failed

Não encontrei alguma explicação que possa ajuda nesse link deles

Aqui está meu packege.json

  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "nodemon src/index.ts --exec ts-node",
    "start": " node dist/index.js",
    "build": "tsc"
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.848.0",
    "axios": "^0.20.0",
    "body-parser": "^1.19.0",
    "jsonwebtoken": "^8.5.1",
    "md5": "^2.2.1",
    "multer": "^1.4.2",
    "multer-s3": "^2.9.0",
    "mysql": "^2.18.1",
    "mysql2": "^2.1.0",
    "nodemailer": "^6.4.10",
    "restify": "^8.5.1",
    "restify-cors-middleware": "^1.1.1",
    "restify-router": "^0.6.0",
    "sequelize": "^6.5.0",
    "sequelize-cli": "^6.2.0",
    "shortid": "^2.2.15",
    "": "^2.3.0",
    "dotenv": "^8.2.0",
    "typescript": "^3.9.6",
    "@types/jsonwebtoken": "^8.5.0",
    "@types/md5": "^2.2.0",
    "@types/multer": "^1.4.3",
    "@types/multer-s3": "^2.7.9",
    "@types/restify-cors-middleware": "^1.0.1",
    "@types/sequelize": "^4.28.9",
    "@types/shortid": "0.0.29",
    "@types/": "^2.1.8",    
    "nodemon": "^2.0.7",
    "reflect-metadata": "^0.1.13",
    "sequelize-typescript": "^2.1.0",
    "ts-node": "^8.10.2"
  "devDependencies": {
  "engines": {
    "node": "14.15.1"

ERROR H10 al desplegar una app nodejs en heroku

hola estoy tratando de subir una app nodejs a heroku pero al desplegarla me sale el error H10, tengo el script Start en el package.json y el puerto bien

app.set('port', process.env.PORT || 3000);

app.listen(app.get('port'), () => {
    console.log('server start in port ' + app.get('port'));

mi package.json

"scripts": {
  "start": "node src/app.js",
  "nodemon": "nodemon src/app.js"

Error en al consol

web hosting – Which options are there to host a NodeJS application?

I’m used to the traditional style of webpages with php as backend html, css and a small amount of js as frontend. But for now I’m learning ReactJS and I’m going to learn Express.js to setup the backend.

To make my application accessible in the internet I need a hosting service. Even though the part of developing an application using React and Express seems to be easier, it seems to be much more difficult to find a good hosting provider that offers nodejs support. For my “traditional projects” (html, css, js: frontend; php: backend) I found good offers for around 2-4€ (~2-4$). But sadly all these offers don’t include NodeJS support. That lead me to write this question and ask you – because you probably know much more about this topic – which options there are to host my node js application for 2-4€ (~2-4$).

My requirements are:

• min. 20 GB SSD storage.
• min. 5 SSD databases (either sqlite or mysql, doesn’t matter)

I won’t have many visitors on my webpage (max. 5k-10k/day), but nethertheless I want a fast website to archive a good user experience. My website is basically an open dashboard (no login or sth. like that) that displays data from 5-10 databases using react and express. The databases get updated every minute and can grow to a size of multiple gigabytes.

I hope you can help me. I’m new to this topic (…and my english skills too…)!

Node.js Buffer.byteLength() throws TypeError exception

    // Construct the message
    var msg = 'Your payment of' + (orderData.paymentIntent.amount / 100) + '$ for the order with order ID ' + + ' has been received successfully';

    // Configure the request payload
    var payload = {
        'from' : 'Mailgun Sandbox <>',
        'to' : 'MAILADDRESS',
        'subject' : 'Order Receipt For Order ID: ' +,
        'html' : msg

    // Stringify the payload
    var stringPayload = querystring.stringify(payload);

    // Configure the request details
    var requestDetails = {
      'protocol' : 'https:',
      'hostname' : '',
      'method' : 'POST',
      'path' : '/v3/',
      'auth' : {
      'username' : 'api',
      'password' : 'API_KEY'
      'headers' : {
        'Content-Type' : 'application/x-www-form-urlencoded',
        'Content-Length' : Buffer.byteLength(stringPayload)

Hi! I have been trying to write a function to send mail via Mailgun and I’ve sort of hit a wall. The above code, whenever I test it out, throws an invalid type error which says:

TypeError (ERR_INVALID_ARG_TYPE): The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object

Oddly enough when I take out the auth object (or just set it up so that it isn’t an object), my code works. I can’t really understand why though. I haven’t used any external libraries, this is just Node.js and since I’m new to Node I couldn’t figure it out on my own. Any help is appreciated so thank you in advance.

node.js – Discrepancy in package-lock.json

I have a macbook and an ubuntu machine. I’ve updated nodejs/npm to the same most recent versions, 15.9.0/7.5.3 respectively. On both machines I check out the same git repository and run npm install, and there’s a small discrepancy in the resulting package-lock.json file. On my mac, there’s this packages / "" / name entry. On ubuntu, there isn’t.

# git diff

diff --git a/package-lock.json b/package-lock.json
index 8c4314e..ac3c36d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -5,7 +5,6 @@
   "packages": {
     "": {
-      "name": "myproject",
       "version": "0.0.1",

As package-lock.json file is supposed to be committed into the git repository, I’ll have to commit package-lock.json every time depending on which machine I work on unless I resolve this issue. I wonder if there’s a right way to avoid that.

express – no funciona en nodejs

estoy haciendo un chat basico con logueo y register. pero tengo un problema y es que no se envian los mensajes, no me sale ningun error y llevo un buen rato intentado que funcione pero nada

codigo de del lado del servidor

    const socketIO = require('');
    const io = socketIO(server);

    io.on('connection', (socket) => {

        io.on('chat:mensaje', function (data) {
             io.sockets.emit('chat:mensaje', data)

codigo del lado del cliente

    <div id="mensajes"> </div>
    <input type="text" id="chat">
    <button id="boton">enviar</button>

    const socket = io();

    output = document.getElementById('mensajes');
    button = document.getElementById('boton');
    input = document.getElementById('chat');

    button.addEventListener('click', () => {
        socket.emit('chat:mensaje', {
            mensaje: input.value

    socket.on('chat:mensaje', (data) => {
        output.innerHTML += '<div>' + data.mensaje + '</div>';
<script src="/"></script>

nodejs – CORS no reconoce la direccion IP de mi frontend

Tengo un problema con Cors en mi backend, Cors indica que la direccion ip que coloque en la lista blanca no es igual a la que usa mi frontend.

Esto es el servicio que envia los datos al backend:

import { Injectable } from '@angular/core';
import { Persona } from '../modelos/persona';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import {HttpClient,HttpErrorResponse,HttpHeaders }from '@angular/common/http'

  providedIn: 'root',
export class PersonaService {

  headers=new HttpHeaders();

  selectedPersona: Persona;
  readonly URL_API='http://localhost:3000/Inicio/Persona';
  constructor(private http: HttpClient) { 
    this.selectedPersona=new Persona();


La petición llega desde que es mi front

En mi Backend establezco la direccion permitida :


Y al final devuelve el error :

Access to XMLHttpRequest at ‘http://localhost:3000/Inicio/Login’ from origin ‘’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘’ that is not equal to the supplied origin.