How can I run background task in node.js - node.js

I saw that I could run background tasks by using nohup node index.js.
My problem is related with following source.
https://github.com/Palpasa/Node-Express-Seed.
In this source, package.json file contains nodemon and it is working when I start the server with npm start.
For now, I tried to run the server in background.
But it is crashing with following error.
[nodemon] 1.14.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
/home/tom/Documents/work/wallet/app/app.js:3
import bodyParser from 'body-parser';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
[nodemon] app crashed - waiting for file changes before starting...
How can I run this server in background?

You can run several screens on your putty.
screen
Then you will have one screen.
You can now run your node instance on this screen.
This screen is alive all the time.
Type CTRL+A+D to go out of the screen.
Your node instance is now always alive even you quit putty.

Child Process is what you would want to use.
const { spawn } = require('child_process');
const otherScript = spawn('node', ['script-you-wanna-run.js']);
otherScript.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});

You probably need to use ES-2015 babel preset to transpile the import statements. If you don't need the ES6 import specifically, just use require
var bodyParser = require("body-parser")
On another note you can try using Forever npm package. This let's you start the node server in the background
FOREVER
npm install -g forever
forever start server.js
// To run on a custom po
PORT=3000 forever start server.js

You cannot run nodemon in the background (i.e nohup npm start <=> nohup nodemon app.js), nodemon supposed to be used for development environment, it let you see what changes are made on files during development, if you are looking for running express app in production, Then you should use a process manager, it restarts the app automatically when it crashes, or when changes are made, read this article for more information. Here is an example using pm2 module:
Install pm2:
npm install pm2 -g
Run app:
pm2 start app.js

Related

NodeJS App 'Module Not Found' when run from Docker

I'm currently in the process of containerizing my App. Part of the App is a NodeJS Express Backend.
It works without any issues when I run it on my console with node index.js or nodemon index.js.
Inside the middlewares/index.js I do import authJwt.js and verifySignup.js via require('./verifySignup) and require('./authJwt).
This works unsurprisingly well when I run my app from the console. However If i build my docker-image using the following Dockerfile-Code:
# build environment
FROM node:14
# Working Directoy
WORKDIR /app
ENV FILE_UPLOADS="./files/uploads"
ENV FILE_UPLOADS_PART="./files/uploads_part"
ENV PORT=3001
ENV DB_HOST="localhost"
ENV DB_USER="root"
ENV DB_PASSDWORD="root_password"
ENV DB_NAME="upload_db"
ENV SECRET_KEY="bezkoder-secret-key"
# Copy Needed Files for Dependencies
COPY package.json /app/package.json
COPY yarn.lock /app/yarn.lock
# Install with YARN
RUN yarn install
# Copy Source Files
COPY ./ /app
EXPOSE 3001
CMD [ "yarn", "start" ]
When I run the Image it immediately terminates. Looking at the logs I find the following error:
$ docker logs 031241ce227a
yarn run v1.22.5
$ node index.js
internal/modules/cjs/loader.js:895
throw err;
^
Error: Cannot find module './verifySignUp'
Require stack:
- /app/middleware/middleware.js
- /app/routes/auth.routes.js
- /app/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)
at Function.Module._load (internal/modules/cjs/loader.js:742:27)
at Module.require (internal/modules/cjs/loader.js:964:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/app/middleware/middleware.js:2:22)
at Module._compile (internal/modules/cjs/loader.js:1075:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1096:10)
at Module.load (internal/modules/cjs/loader.js:940:32)
at Function.Module._load (internal/modules/cjs/loader.js:781:14)
at Module.require (internal/modules/cjs/loader.js:964:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/app/middleware/middleware.js',
'/app/routes/auth.routes.js',
'/app/index.js'
]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I then exported my docker-image using docker export adoring_kowalevski > contents.tar to look at the filesystem inside the image, but everything is where it should be.
In a desperate attempt I hoped, that the issue might occur because I have multiple index.js in different folders, so I changed the names of all except the one in the root directory, but issue persisted. This is why in the error-log there is a middleware/middleware.js, it was after renaming the middleware/index.js.
Edit:
I tried using rfr to change my references from require('../middleware') to rfr('middleware'). It still workds from console but still not inside the container. So it seems that the issue doesn't occur because of the relative file paths.
Turns out I'm stupid (somewhat).
The import inside middleware/index.js looked like this require('./verifySignUp').
If we look at the file verifySignup.js inside the middleware Folder we can see, that it is named without the capital 'U'.
Why did it still work from console?
Inside verifySignup.js is the following piece of code:
module.exports = {
authJwt,
verifySignUp
};
Here it is written with capital 'U'. This means that running node index.js from the console only cared about whatever was written in the module.exports and not the actual Filename, however when running inside Docker, the Filename matters.
Renaming the file from verifySignup.js to verifySignUp.js solved my problems.

Nodemon app cannot find module when restarting

I'm currently building a RESTful API. I start my MongoDB server using the command mongod. When I restart my Node server (using rs), however, it throws the following error:
[nodemon] starting `node todoListApi`
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'C:\Users\Zakaria5\Desktop\Stage Technique
2019\zen-networks-backend\todoListApi'
at Function.Module._resolveFilename
(internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
I Googled this error, and the solution seemed to be to remove the node_modules directory. However, when I type rm -rf nodes_modules, it displays that the command is not found. I also tried using npm install and npm start, but this throws an error, as well. What am I doing wrong?
I resolve the problem by fixing the path !! Well , when i type npm install and npm start ! It displays an error which confirms that the file isnt available in a path by default !! (in my case) C/users/Zakaria/package.json !! when i look for that file i didnt find it ! Thus , I have to change the path which contains my package.json file . I used that command " npm start --prefix TheRealPath " Hence , the RESTful API starts on port : 3000 !! :P

Node JS error: Cannot find module '../build/jvm_dll_path.json'

I am receiving the following error after running npm start:
Error: Cannot find module '../build/jvm_dll_path.json'
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/opt/stature-gqdss/node_modules/java/lib
[nodemon] app crashed - waiting for file changes before starting...
Can you help me with this issue?
First, you should check if the server is already running and kill the existing server. If no other server is running, try reinstalling your dependencies and try again.
npm install
I have a hack here. You can simply create a file named jvm_dll_path.json inside node_modules\java\build and paste the path of server to this, between quotes like shown below..
";C:\\Program Files\\Java\\jdkX.X.X_XXX\\jre\\bin\\server"
For me running
node postInstall.js
in the node_modules/java folder worked.

Heroku Scheduler - When I try to run heroku run node, I get an error

I'm trying to create some cron jobs via the Heroku scheduler plugin. I've tested my node script on my local machine and it works fine, however, when I commit and push to heroku, when I run heroku run node check_work_orders.js, I get this error:
Running node check_work_orders.js on ⬢ fms-sandbox... up, run.4992 (Free)
module.js:471
throw err;
^
Error: Cannot find module '/app/check_work_orders.js'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
For reference, I was following this guide.
What am I doing wrong here?
Since my node file was location in my app/check_work_orders.js file, I needed to run heroku run node app/check_work_orders.js. This solved my problem. It was just a matter of running node in the correct directory on the Heroku server.

Forever errors with babel-node

I have a simple node server:
//server.js
import express from 'express';
import React from 'react';
...
When I try to run this using Forever:
forever start -c "babel-node --experimental" server.js
, it errors out due to use of import
/Applications/MAMP/htdocs/React/ReactBoilerplates/koba04/app/server.js:1
(function (exports, require, module, __filename, __dirname) { import express
^^^^^^
SyntaxError: Unexpected reserved word
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
error: Forever detected script exited with code: 8
I have also tried pm2 and nodemon, I get same error there as well.
For pm2, I followed this issue https://github.com/Unitech/PM2/issues/1167, but it didn't work either. What am I doing wrong here?
forever start -c "node -r babel-register" ./src/index.js
Also works.
This works for on-the-fly transpilation for me: forever start -c node_modules/.bin/babel-node server.js
Another solution is using the Require Hook like this:
// server-wrapper.js
require('babel/register');
require('./server.js');
Then run forever start server-wrapper.js.
I suggest to precompile your es6 scripts into es5 scripts and run the app with a forever start server.js command where server.js is a result of precompilation.
If you're using react.js for an isomorphic app you also will be needed to precompile your scripts for browsers either (via browserify, webpack and so on).
So I see no profit to work with es6 scripts via on demand compilation versus precompilation with gulp or any other js building system.
In your package.json file under scripts tag add entry like below
in package.json under scripts tag
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "forever start -c babel-node src/index.js",
},
all the dependencies must include in dependencies tag in package.json file
then do a npm install then
run the server by executing npm start

Resources