Running a React app as a background process - javascript

I'm completely new to deploying front-end code and thus the question.
I have a React App which I need to run as a background process, however I'm a little confused about the how to do this.
I run a npm script
npm run build
to build, minify and serve the project on a server.
The relevant code for the build process is this.
"prebuild": "npm-run-all clean-dist test lint build:html",
"build": "babel-node tools/build.js",
"postbuild": "babel-node tools/distServer.js"
This is the code inside the distServer.js
import express from 'express';
import path from 'path';
import open from 'open';
import compression from 'compression';
const port = 3000;
const app = express();
app.use(compression());
app.use(express.static('dist'));
app.get('*', function(req, res){
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
app.listen(port, function(err){
if(err){
console.log(err);
}else{
open(`http://localhost:${port}`);
}
});
This works and the project runs, however the moment I close my terminal the project stops.
The build process creates, three files,
index.html
index.js
styles.css
Now if I navigate to the index.html and open it in a browser, but naturally, nothing shows up. So I'm assuming that I'd have to run it as a node process. How do I do this on the production server and run it as a background process so that even if I exit the terminal the app continues to run.
I have checked this issue,
How to make a node.js application run permanently?
But this has a javascript file as the entry point, in my case it's a html file. I'm not sure how can I modify my scripts to run the front-end app permanently as a background process. Any help appreciated.

Your Javascript file (distServer.js) is your entry point – it's the file that you run to start your server. Your HTML file (index.html) is only served as a response to the requests.
babel-node is OK for development, but it's not suitable for production. You can precompile your Javascript files to vanilla Javascript, then use forever or pm2 as described in the question you already linked to in order to keep the server running even after you close your terminal.
How you organize your source files and compiled files is up to you, but here's one way to do it (quote from the documentation for an example Node server with Babel):
Getting ready for production use
So we've cheated a little bit by using babel-node. While this is
great for getting something going. It's not a good idea to use it in
production.
We should be precompiling your files, so let's do that now.
First let's move our server index.js file to lib/index.js.
$ mv index.js lib/index.js
And update our npm start script to reflect the location change.
"scripts": {
- "start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
+ "start": "nodemon lib/index.js --exec babel-node --presets es2015,stage-2"
}
Next let's add two new tasks npm run build and npm run serve.
"scripts": {
"start": "nodemon lib/index.js --exec babel-node --presets es2015,stage-2",
+ "build": "babel lib -d dist --presets es2015,stage-2",
+ "serve": "node dist/index.js"
}
Now we can use npm run build for precompiling our assets, and npm run serve for starting our server in production.
$ npm run build
$ npm run serve
This means we can quickly restart our server without waiting for
babel to recompile our files.
Oh let's not forget to add dist to our .gitignore file.
$ touch .gitignore
dist
This will make sure we don't accidentally commit our built files to
git.

Related

Where is json.config file found in the root of the project?

I am new in development field.
I have already made an app in create-react-app.
But now I have been asked to submit json.config file..
It is mentioned that -
The file must be called config.json and must be stored in the root level of your project.
Here is the format of the configuration file:
{
"install": "npm install",
"run": "npm start",
"port": 3000
}
I am unable to find it in my project folders and dependency folders and files.
Create-React-App creates this file for you under the hood. So you don't have to setup it. You can open the terminal and write npm install and after npm start. That will open your web app in http://localhost:3000.
More details https://create-react-app.dev/docs/available-scripts
Edit: Dependencies should be inside the package.json in the root directory.

how to create production build in node js?

I am new in nodejs framework .I read the tutorial, but I want to know how to create a build in node js, in other words I need a script which create my build folder.
I follow these steps
create index.js in root directory add some code.
then add this line of code
import express from 'express';
const app = express();
app.listen(3000,function () {
console.log(`app is listening on 3000`)
})
in my package.json I added start and build script
"scripts": {
"start": "nodemon ./index.js --exec babel-node -e js",
"build": "mkdir dist && babel src -s -d dist"
},
when I do npm run start .my application run fine and I am able to debug also.
Now I want to deploy this application on production Need build.so how to generate build using babel
when I run npm run build I am getting error
src doesn't exist
You 'build' command is like 'mkdir ... && babel src ....', then in the photo it does not have a src folder. So you can simply create a src folder and move index.js to src/, or change the command to 'mkdir dist && babel ./ -s -d dist'. I did not test, but it should work.

About MEAN 2 stack using angular-cli

I'm studying MEAN 2.0 . I need to do "ng build" before running "node server.js".
I would like to ask if do I need to do (ng build) everytime I changed something in my angular side? Because when I'm using only angular-cli, when I changed something and my server is still running. It will show the changes. I tried to change something but when I re-run my node server nothing happens.
Yes you need to do ng build before running node server.js.
ng serve :- serves on a server,
node server.js :- doesnt serve on the same port, it runs on the port you define in your server.js, it reads from the build folder, which will need updated fies.
Live reload wont work :(
You can
1. write tasks for it
2. write script in package.json which does ng build && node server.js
If you arranged your folder structure to be:
|_server
|_ server.js
|_ public (angular-cli project)
|_ dist
|_ src
|_ package.json (client)
|_package.json(server)
Considering you've the default angular-cli package.json,
Add concurrently using npm:
npm install concurrently --save-dev
All you would need is to add those scripts in server package.json:
"scripts": {
"client":"cd public && ng build",
"server":"ndoe ./server/server",
"start":"concurrently --kill-others \"npm run client\" \"npm run server\""
}
Now, all you have to do is:
npm run start

NodeJS - nodemon not restarting my server

I installed NodeJS (4.4.5) and then proceed to install nodemon (1.9.2) as well,
I follow all the instrucctions of instalation (npm install -g nodemon)
I created a new folder, inside I have my server.js with some basic code:
var http = require('http');
http.createServer(function (request, response){
response.writeHead( 200, {'Content-Type': 'text/plain'} );
response.write("Hello world");
response.end();
}).listen(3000, 'localhost');
console.log('http://localhost:3000');
So when I run in my console "nodemon server.js" I get this:
[nodemon] 1.9.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
http://localhost:3000
(Which means that is running fine)
But when I make some changes in my server.js, It doesn't restart the server
What could be the issue?
In some networked environments (such as a container running nodemon reading across a mounted drive), you will need to use the legacyWatch: true which enabled Chokidar's polling.
Via the CLI, use either --legacy-watch or -L for short:
nodemon -L
I had the same issue on nodemon 1.9.2 : 0 files were watched by nodemon
(try verbose mode nodemon server.js -V to get more information)
After some research, this issue was due to my root directory name :
My root directory was named "mysite.git" thus nodemon was watching 0 file. I had renamed my root directory without the dot and nodemon now works as expected.
Remove all special characters from your root directory and nodemon should work as expected.
You can try running like this nodemon -L yourapp.js, something like that:
"scripts": {
"start": "node index.js",
"dev": "nodemon -L index.js "
}
And run command:
npm run dev
This worked for me!
I just hit what seemed to be the same issue where I would make changes to my code and save them but nodemon wouldn't restart my server. The only way I could update was via 'rs' in the console. I ended here looking for a solution but then decided to just re-install nodemon as there was no good explanation for why it wasn't working:
npm uninstall nodemon
npm install nodemon
After reinstalling the automatic restart on code change worked.
Nodemon uses SIGUSR2 signal for restarting the server, cross-check if your server is overriding the functionality of this process signal.
In my case, I was using heapdump module, which was resetting this signal, hence I started the server using:-
env NODE_HEAPDUMP_OPTIONS=nosignal nodemon app.js
This worked for me.
Edit the package.json file like this :
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js",
},```
This may help you.
Just Make Sure to add to scripts -> start --legacy-watch ./app
"scripts": {
"start": "nodemon --legacy-watch ./app ./bin/www "
},
I had the same problem. I tried uninstalling nodemon, didn't work. You can try and uninstall nodemon globally, if it works. It didn't work in my case, so what I did is I deleted all the node modules from my system. They will be located at C:/users/user/AppData/Roaming/npm. I even reinstalled node into my system and then installed nodemon, then it worked.
I had the same problem and I solved it adding the path C:\Windows\System32 to the system environment, after that, I had to restart Visual studio code and it worked!...
Reference: https://www.youtube.com/watch?v=a9fIZViTNEA
if you are on windows use Powershell, not WSL. If you want to use WSL, you have to move your project directory to the WSL home directory OR use nodemon -L on the command line.
solve it by adding the path
C:\Windows\System32
to the system environment
Source: https://www.youtube.com/watch?v=a9fIZViTNEA
I found a solution on YouTube. So, the solution is:
Copy this path:
C:\Windows\System32
Go into 'computer/This Pc' properties then into 'Advance System Settings/System Settings'.
Then click on 'Environment variable' Button.
Then double click on 'Path' in User Variables section.
Then click on 'New' and paste this path :
C:\Windows\System32

Node.js with express - npm start do not work

I have problem trying to run node app in Windows 7.I have installed express generator globally and with it help created a test_app directory and installed the modules. In the package.json scripts look like this:
"scripts": {
"start": "node ./bin/www"
}
However, when i run npm start it just returns this in console:
test_app#0.0.1 start C:\work\test_app
node ./bin/www
If i try to run node app.js nothing happens. Before there wasn't problems with the express, until the moment when i had to install express-generate globally.

Categories