Node js перезапуск скрипта при ошибке

How would I be able to restart my app when an exception occurs?

process.on('uncaughtException', function(err) {         
  // restart app here
});

hexacyanide's user avatar

hexacyanide

87.6k31 gold badges159 silver badges161 bronze badges

asked Oct 12, 2013 at 16:15

You could run the process as a fork of another process, so you can fork it if it dies. You would use the native Cluster module for this:

var cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();

  cluster.on('exit', function(worker, code, signal) {
    cluster.fork();
  });
}

if (cluster.isWorker) {
  // put your code here
}

This code spawns one worker process, and if an error is thrown in the worker process, it will close, and the exit will respawn another worker process.

answered Oct 12, 2013 at 16:24

hexacyanide's user avatar

hexacyanidehexacyanide

87.6k31 gold badges159 silver badges161 bronze badges

2

You have a couple of options..

  1. Restart the application using monitor like nodemon/forever
process.on('uncaughtException', function (err) {       
    console.log(err);
    //Send some notification about the error  
    process.exit(1);
});

start your application using

  • nodemon
nodemon ./server.js 
  • forever
forever server.js start
  1. Restart using the cluster

This method involves a cluster of process, where the master process restarts any child process if they killed

var cluster = require('cluster');
if (cluster.isMaster) {
   var i = 0;
   for (i; i< 4; i++){
     cluster.fork();
   }
   //if the worker dies, restart it.
   cluster.on('exit', function(worker){
      console.log('Worker ' + worker.id + ' died..');
      cluster.fork();
   });
}
else{
   var express = require('express');
   var app = express();

   .
   .
   app.use(app.router);
   app.listen(8000);

   process.on('uncaughtException', function(){
      console.log(err);
      //Send some notification about the error  
      process.exit(1);
  });
}

FredTheWebGuy's user avatar

answered Oct 12, 2013 at 16:36

Sriharsha's user avatar

SriharshaSriharsha

2,3581 gold badge16 silver badges20 bronze badges

2

checkout nodemon and forever. I use nodemon for development and forever for production. Works like a charm. just start your app with nodemon app.js.

answered Oct 12, 2013 at 16:21

kel c.'s user avatar

kel c.kel c.

3231 silver badge5 bronze badges

In this article, we are going to learn, about restarting a Node.js application when an uncaught exception happens. For this, we are going to use the pm2 module.

Approach: Let’s see the approach step by step:

  • Step 1: Install the pm2 module and use it to start the server.
  • Step 2: When an uncaught exception happens, then execute the command process.exit() to stop the server.
  • Step 3: Then, pm2 module will automatically start the server again.

process.exit() stop the server and pm2 force it to start. In this way, the server will restart.

Implementation: Below is the step-by-step implementation of the above approach.

Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express pm2

To install express and pm2 as dependencies inside your project

Step 3: Creating a list of products: Let’s create an array of products and set it to constant products.

const products = [];

Step 4: Creating Routes for the home page and the products page: Let’s create two routes so that users can access the home page and the products page.

app.get('/', (req, res) => {
   res.send('Hello Geeks!');
});

app.get('/products', (req, res) => {
   if (products.length === 0) {
       res.send('No products found!');
       process.exit();
   } else {
       res.json(products);
   }
});

Inside the product route, we use process.exit() method to stop the server.

Complete Code:

Javascript

const express = require('express');

const app = express();

const products = [];

app.get('/', (req, res) => {

    res.send('Hello Geeks!');

});

app.get('/products', (req, res) => {

    if (products.length === 0) {

        res.send('No products found!');

        process.exit();

    } else {

        res.json(products);

    }

});

app.listen(3000, ()=>{

    console.log('listening on port 3000');

});

Steps to run the application: Inside the terminal type the command to run your script ‘app.js’ with pm2.

pm2 start app.js

Output:

Last Updated :
18 Jul, 2022

Like Article

Save Article

  • Главная

  • Инструкции

  • Node.js

  • Автоматический перезапуск приложений Node.js с помощью nodemon

Blog

В Node.js для применения любых внесенных изменений требуется перезапуск процесса. Если идет активная разработка, это добавляет к работе дополнительный шаг, который надо повторить неоднократно, периодически. Его можно убрать при помощи утилиты nodemon, предназначенной для перезапуска процессов в автоматическом режиме.

Как Автоматически Перезапускать Приложения Node.js С Помощью Nodemon

Принцип работы приложения заключается в размещении среды внутри своеобразной «оболочки» для мониторинга файловой системы и перезапуска процесса. В этой статье мы последовательно разберем, как провести установку nodemon на машине с Node.js, так и настройку утилиты, использование встроенных в нее опций и конфигураций.

Требования к системе

Понадобится локальная машина или виртуальная VPS/VDS на облачном сервере, подходящая по техническим характеристикам. Они включают минимум процессор с тактовой частотой 1 ГГц, ОЗУ от 512 Мбайт, свободное пространство на накопителе от 15 Мбайт. Также нужно произвести установку Node.js по инструкции из официальной документации, создать среду разработчика (а это уже тема для отдельной статьи).

Первым этапом всегда идет установки утилиты на рабочем или виртуальном компьютере. Есть два варианта – глобальная и локальная инсталляция. Выполнить процедуру можно через npm или yarn.

Установка в глобальном режиме

Выполним команду через npm:

npm install nodemon –g

Или yarn:

yarn global add nodemon

Установка в локальном режиме

При локальной инсталляции допустимо задавать зависимость dev:

npm install nodemon --save-dev

При помощи yarn команда будет выглядеть так:

yarn add nodemon –dev

Процедура установки завершена, можно приступать к дальнейшей работе.

Шаг 2. Настройка проекта Node.js через nodemon

С практической стороны интересна возможность старта скриптов Node с nodemon. Возьмем пример: в наличии есть файл для задания параметров, сохраненный под именем serv.js. Введем команду и понаблюдаем за происходящими корректировками:

nodemon serv.js

При запуске допускается передавать аргументы в том же порядке, как будто скрипт запускается при помощи Node:

nodemon serv.js 3006

Процесс перезапустится после каждой корректировки файлов. Речь идет только об отслеживаемых расширениях (.js, .mjs, .json, .coffee, .litcofee) и текущей папке. В качестве примера возьмем все тот же файл serv.js и внесем в него команду на вывод сообщения: 

Dolphin app listening on port ${port}. 

Теперь введем команду:

nodemon serv.js

На экран будет выведено сообщение:

[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting  `node serv.js`
Dolphin app listening on port 3000!

Пока утилита функционирует, сделаем корректировки в файле serv.js. Например, чтобы скрипт вывел сообщение Shark app listening on port ${port}. Информация на экране обновится, мы увидим:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Shark app listening on port 3000!

Как и планировалось, идет вывод о произведенных изменениях. Рестарт процесса возможен по желанию пользователя – достаточно набрать команду rs и кликнуть Enter.

Шаг 3. Применение опций

Конфигурация утилиты nodemon управляется путем применения различных опций, вводимых в командной строке. Рассмотрим часть из них, которые встречаются чаще остальных:

  • --exec – задает двоичный код, считываемый при выполнении файлов. Так, в случае указания ts-node утилита будет наблюдать за запуском TypeScript, происходящими в нем изменениями.
  • --ext – опция указывает утилите nodemon, какие расширения будут подпадать под функцию наблюдения. Вносить перечень следует через запятую. Например, js, ts.
  • --delay – устанавливает время до перезапуска процесса после фиксации изменений в файле. По умолчанию это значение равно одной секунде. Новое требуется указывать в цифровом виде, например 3.1.
  • --watch – позволяет задать наблюдение за несколькими файлами или директориями. Опцию используют отдельно для каждого объекта. По умолчанию утилита мониторит текущую папку и вложенные в нее каталоги. При помощи watch можно как расширить сферу работы nodemon, так и сузить сектор наблюдения, отключив часть вложенных папок или файлов, расположенных в них.
  • --ignore – аналогично предыдущей опции, предназначена для принудительного отключения наблюдения за указанными файлами, папками или шаблонами.
  • --verbose – дает подробное информирование об измененных файлах, процедуре рестарта процесса.

Полный перечень опций доступен по команде:

nodemon --help

Приведем пример их комбинированного использования. Предположим, что необходимо включить мониторинг файлов с расширением .ts в каталоге server, при этом пропускать файлы с суффиксом .test.ts и ждать рестарта в течение 3-х секунд после фиксации факта сохранения изменений. А также при запуске применять двоичный код ts-node.

Команда будет выглядеть так:

nodemon --watch server --ext ts --exec ts-node --ignore '*.test.ts' --delay 3 server/server.ts

Здесь одновременно используются опции --watch, --ext, --exec, --ignore и --delay.

Шаг 4. Применение конфигураций

Если думать о том, как упростить работу с Node.js, стоит настроить и параметры конфигурации. Например, задать перечень нужных опций в nodemon.json. Тогда появится возможность пакетного старта утилиты. Пример такого файла:

{
  "watch": ["server"],
  "ext": "ts",
  "ignore": ["*.test.ts"],
  "delay": "3",
  "execMap": {
    "ts": "ts-node"
  }
}

Здесь execMap заменяет оператор exec. Он разрешает указывать двоичный код, подключаемый при обработке указанных расширений файлов.

Есть другой вариант добавления конфигурации – скорректировать файл package.json, данные будут расположены в ключе nodemonConfig:

{
  "name": "test-nodemon",
  "version": "1.0.0",
  "description": "",
  "nodemonConfig": {
    "watch": [
      "server"
    ],
    "ext": "ts",
    "ignore": [
      "*.test.ts"
    ],
    "delay": "3",
    "execMap": {
      "ts": "ts-node"
    }
  },
  // ...

После сохранения nodemon.json или package.json можно запускать утилиту при помощи скрипта:

nodemon server/server.ts

Приложение подхватит конфигурацию и начнет работать в соответствии с заданными параметрами. Такой подход позволяет быстро настраивать новые системы и передавать настройки другим, чтобы не тратить время на синхронизацию командных компьютеров.

Заключение

Мы рассмотрели краткую информацию по инсталляции и настройке утилиты nodemon для контроля обновлений файлов в среде Node. Это решение популярно благодаря автоматизации рутинных задач остановки-запуска сервера. При отсутствии под рукой локальной машины для экспериментов, стоит взять в аренду мощности у провайдера Timeweb Cloud.

Asked
5 years, 3 months ago

Viewed
222 times

I have a nodejs script which crashes sometimes. I have used forever to restart the script upon crashing. Now there is a problem, some errors make it so that I need to wait a specific time before I can restart the script. How would I go about handling the different errors so that the script gets instantly restarted on every crash except the one where I Need to wait for 30 minutes.

  • node.js

asked Mar 23, 2018 at 9:12

teddy's user avatar

teddyteddy

531 silver badge3 bronze badges

5

  • What kind of error msg do you get?

    Mar 23, 2018 at 9:46

  • Can you detect the error which needs 30mn of waiting before it arrives ? If yes, you can have another script managing the forever rules for your main script and which will wait the 30mn and then launch the main script again.

    Mar 23, 2018 at 9:49

  • I get an error object and I can identifiy on which error I have to wait. How would I go about managing a script from another script, and handling errors then.

    Mar 23, 2018 at 10:36

  • try something like systemd to run the node server

    Mar 23, 2018 at 12:22

Load 7 more related questions

Show fewer related questions

  • The Overflow Blog
  • Featured on Meta

Hot Network Questions

  • Letting drawings ignore a contour without drawing over the label

  • Have Jonathan Pie’s «allegations» been supported by the Privileges Committee report? «he lied, and did it again by denying that he’d previously lied»

  • If checked baggage / luggage size limit is 62-inch. Isn’t most luggage sets oversized?

  • If a moderator of an online forum edits my post to say something illegal, how could I prove I didn’t write the incriminating message?

  • Write full box to topology file + script representation

  • Can mowing weeds cause them to spread?

  • What to do if a core function does exactly what you need to do, but has a bug

  • Constexpr flat_multimap

  • problem aligning equation to text

  • Writing a separate package vs copy pasting small amount of reused code

  • How to verify that multipart zip file is valid

  • Movie involving a spaceship with upright sleep pods; a female crew member gets trapped inside one and can’t wake up

  • Attack with more than 2 weapons without having 3 or more arms?

  • If Boris Johnson returns as an MP, would he have to serve the 90-day suspension for lying to Parliament?

  • Can dark matter accumulate at Lagrange points?

  • How Exactly Do I Balance Combat Encounters In D&D With The Rules From The DMG?

  • Is there an inherent legal obligation to repay a guarantor?

  • Which Paris metro station to alight for CDG international airport?

  • What would a Medieval-Tech «super-metal» look like?

  • What is the proper etiquette when declining a professor’s Capstone project offer after I myself applied for it?

  • Fine-tuning LLM or prompting engineering?

  • Name of a 1970’s ESP/Psychic-themed «docudrama» series?

  • How do I get such colorful plots with bar legends colored like this?

  • What is causing the pilot light to go out with a loud clunk?

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Всем привет.
Я начинающий программист. И знаю, что при программировании появляются подводные камни и с ними надо бороться. Но тут проблемка интересная, возможно кто подскажет или поделиться ссылкой на другой ресурс, в котором я смогу найти ответ.

Так вот ближе к теме. У меня есть свой телеграм бот- напоминалка. Програмнно бот реализован на js с библиотекой telegraf.js. Он присылает напоминания пару раз в день. Все работает отлично. Но, как всегда есть слово — но.

Мне нужно, чтобы бот работал 24-ри часа в сутки. Для этого я выделил системник на котором настроил в биосе включения по питанию. Запуск бота поместил в батовский файлик в нем прописано:

start npm run start
cmd cd D:папка с ботом — в которой лежыт app.js

Этот батовский файл я закинул в автозагрузку виндовс. Тоесть при отключении и включении электроэнергии системник стартует, потом виндовс и автозагрузка бота. Как бы все нормально. Но, не тут то было.
При запуске бота не всегда есть интернет он может появиться после 10-20 минут после старта бота. Соответственно, при старте запускается cmd в котором запускается окно npm в котором работает бот:
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`

и тут выдает 3 ошибки:
(node:10496) UnhandledPromiseRejectionWarning: FetchError: request to https://api.telegram.org/bot…..
(node:10496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `—unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_reje…). (rejection id: 1)
(node:10496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `—unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_reje…). (rejection id: 2)

Скорей всего программа должна подключиться к телеграмму и к node. B ей надо интернет для регистрации каких-то модулей.
Проблема в том, что при появлении интернета программа так и висит с ошибкой и не работает. То есть, надо настроить перезапуск приложения (ну например раз в 15 минут) и если интернет есть, то оно стартанет и все заработает. Так вот вопрос как можно сделать перезапуск приложения програмнно?

Буду очень благодарен за любую помощь.

Возможно, вам также будет интересно:

  • Node js ошибка 500
  • Node js вывод ошибок
  • Node js server side javascript ошибка
  • Node index js ошибка
  • Node exe ошибка приложения

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии