Handling absolute urls in nodejs server - node.js

this is my firs project with electron and nodejs
I need to load a specific folder in my electron application
the final structure should be like:
Myapp.app
folder-contents
MyApp must read contents from folder-contents directory
import httpServer from './server'
function createMainWindow() {
const window = new BrowserWindow()
if (isDevelopment) {
window.webContents.openDevTools()
}
window.loadURL(`http://localhost:18081/${app.getAppPath()}/folder-contents/`)
}
in server.js
const path = require("path");
const http = require('http');
const express = require('express');
const PORT = 18081;
const app = express();
app.use(express.static(process.cwd()));
app.set('port', PORT);
const server = http.createServer(app);
server.listen(PORT, "127.0.0.1");
module.exports = app;
In my package.json
"scripts": {
"dev": "electron-webpack dev",
"compile": "electron-webpack",
"dist": "yarn compile && electron-builder",
"dist:dir": "yarn dist --dir -c.compression=store -c.mac.identity=null",
"start": "electron ."
},
launching npm run dist --mac and open myapp.app i get this error
Cannot GET /folder-contents/
any idea?

you can add your files to a folder name public and inside that you can have all your static files stored and then you need to call it in your app.js like:
app.use(express.static('public') //Public is the name of the folder and then you might be able to use all of your static files presented in that folder in your project if this didn't clear you here's a refrence if i am wrong and you get the correct answer else where please correct me.Thank you.
This is an express documentation

Related

Prevent Nodemon to restart some specific code

I'm using nodemon in my nodejs project because I want whenever I made any changes it will restart automatically everything works fine but now problem is I want to use a lib
which include puppeteer lib whenever I made any changes nodemon close the chromium browser and re-open it which take some time. This is making me slow in development. Is there any way I can stop this behaviour.
Here is my code.
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Client } = require("whatsapp-web.js");
const client = new Client({ puppeteer: { headless: false } });
client.initialize();
console.log("changes 7");
server.listen(3000, () => {
console.log("listening on *:3000");
});
Whenever I made any changes it restart everything. I don't want to restart the client every time.
I don't know about nodemon, but if you can edit the library, you can re-use an existent browser.
Try, from node shell:
(await require('puppeteer').launch()).wsEndpoint()
this return a connection string that you can reuse.
And, then, you can connect with the created instace with connect api
Edit: your library allows ws socket! :-)
const client = new Client({
puppeteer: {
browserWSEndpoint: `ws://localhost:3000`
}
});
create nodemon.json in your project directory
nodemon will automatically look for this file and use it if exist
and write in nodemon.json
{
//list of directory you want to watch
"watch": ["./","server","someOtherDir"],
"ext": "js,ts,json", //file extension to watch
"ignore": ["ignoreThisDir","someDir/*.js"], //specify files or directory to ignore
// specify entry of the project
"exec" : "node app.js"
//another example for exec "exec": "ts-node --project tsconfig.server.json server/app.ts"
}

How to properly configure Next.js as a frontend and Express app as a backend?

Currently I have create-react-app for frontend and express server for backend. In package.json of my create-react-app I use proxy like this "proxy": "http://localhost:5000".
I need to achive the same thing for Next.js app with the same express server.
I just want to be able to use my express server instead of API routes built in Next.js and proxy it like I do in create-react-app.
Do I need to create custom Next.js server even though i'm not changing any of it's functionality? How to do this properly?
yes you have to add custom server in next js
install express js then add file server.js in root directory of next js project
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.use(bodyParser.json())
// add custom path here
// server.post('/request/custom', custom);
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('Ready on http://localhost:5000')
})
})
after that change package.json file script section
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js",
}

Problem when Client (react) and Server(nodejs) are in the same folder

I'm trying to deploy my web application, that has my client and server at the same main folder, to Heroku and I face some annoying problem that the server isn't serving the react build folder.
Here's my project folder tree:
/client
/api
app.js
server.js
app.js => routes, loading models, controllers, etc
server.js => server configuration
Here's the content of server.js, I believe the problem is here
const app = require('./app');
const path = require('path');
const cors = require('cors');
const express = require('express');
app.use(cors())
if (process.env.NODE_ENV === "production") {
console.log('we are on production!')
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
console.log('redirecting to react app build')
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on PORT ${port}`))
It never gets to the console.log('redirecting to the react app build') part
When I entered my heroku server I face the server side instead of my react build. why is that so?
I've just created a test project using your architecture. My project is running and uploaded on Heroku right now. I'm gonna detail all steps I just do to make it works according to given information.
So my project architecture :
client/ // from CRA
package.json
server.js
.env
Configure your environment variable :
heroku config:set NODE_ENV=production // this for production heroku
In my .env file I set local environment variables such as :
NODE_ENV=production
Here's my main package.json file which I defined a heroku-postbuild to create the client build folder.
{
"name": "foo",
"version": "1.0.0",
"main": "index.js",
"license": "mit",
"dependencies": {
"cors": "2.8.5",
"express": "4.17.1",
"path": "0.12.7"
},
"scripts": {
"start": "node server.js",
"heroku-postbuild": "cd client && yarn && yarn build"
}
}
And the server.js file, almost the same as the one provided
const path = require('path');
const cors = require('cors');
const express = require('express');
const app = express()
app.use(cors())
if (process.env.NODE_ENV === "production") {
console.log('we are on production!')
app.use(express.static('client/build'));
app.get('*', (req, res) => {
console.log('redirecting to react app build')
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on PORT ${port}`))
You can run Heroku in local by typing this command heroku local in will loaded the .env file with environment variables.
To test production Heroku you have to type heroku open. Don't forget to set up "production" environment variable with command I wrote above.
Everything's working fine. I can upload my code to Github if you want me to.

Use newrelic in nuxt

I am trying to add newrelic agent to my nuxt application. I have installed the needed package and added my license key and set an application name in newrelic.js configuration file:
npm i newrelic
cp node_modules/newrelic/newrelic.js .
nano newrelic.js
My problem is that I also need to require this configuration file at the top of my server.js file and since this file is dynamically created and placed under the .nuxt folder I have no idea how to do this.
In a standard nodejs application I would simply add the require('newrelic'); to the top of my startup script or perhaps add a new script entry in package.json looking something like this:
"scripts": {
"dev": "node -r newrelic.js app.js"
}
I ended up using express to solve this:
npm i express
touch server/index.js
We will now load newrelic in the server/index.js file and after that create our nuxt instance:
require('newrelic');
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const app = express();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js');
config.dev = process.env.NODE_ENV !== 'production';
async function start () {
// Init Nuxt.js
const nuxt = new Nuxt(config);
const { host, port } = nuxt.options.server;
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
// Give nuxt middleware to express
app.use(nuxt.render);
// Listen the server
app.listen(port, host);
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
});
}
start();
I also updated the script section in my package.json:
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js"
}
Hope this can help anyone who faces the same kind of problem.
For anyone struggling with this I found a much simpler solution by using Nuxt modules and hooks.
Create a new file modules/newRelic.js with the following content:
module.exports = function () {
this.nuxt.hook("listen", () => {
require("newrelic");
});
};
Import the module in nuxt.config.js
modules: [
"~/modules/newRelic.js"
]
Don't forget to install newrelic (npm i newrelic) and paste newrelic.js into the applications root folder.
In Node.js, you can require a module with the -r [module] syntax (see Node.js docs) before your actual script starts up.
For Nuxt, alter your npm run scripts like this (instead nuxt start):
node -r newrelic node_modules/nuxt/bin/nuxt.js start
This way, Node loads NewRelic first, then Nuxt, and ensures NewRelic is able to instrument all dependencies. If you let Nuxt bootup first, NewRelic is not aware of some dependencies, e.g. express.
This is recommended by NewRelic, see their docs.

How to run an Angular app on a Node server?

I would like to run my app with express on a Node server.
My server.js file:
var express = require('express');
var path = require('path');
var app = express();
app.get('/', (req, res) => {
res.sendFile(path.resolve('dist/my-app/index.html'))
});
app.listen(80, () => {
console.log('Server started!')
})
But when I'm trying to view my website on localhost nothing appears. Can you help me?
Hope this would help you.
1) Run:
ng build --prod
This will create a dist folder. Used for production.
2) Run:
npm install --save express
To install express and save it as dependency in the project.
3) Create a file in root: ./server.js
4) Copy this code. Don't forget to modify with your name project
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
const port = process.env.PORT || 3001;
app.use(express.static(__dirname + '/dist/my-app-name'));
app.get('/*', (req, res) => res.sendFile(path.join(__dirname)));
const server = http.createServer(app);
server.listen(port, () => console.log(`App running on: http://localhost:${port}`));
5) To run the server.js file
node server.js
I found a solution !
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const port = process.env.NODE_PORT || 3000;
const root = path.join(__dirname, 'dist', 'my-app');
app.get('*' ,function(req, res) {
fs.stat(root + req.path, function(err){
if(err){
res.sendFile("index.html", { root });
}else{
res.sendFile(req.path, { root });
}
})
});
app.listen(port);
console.log('Listening on port '+ port);
You can do this in just very few steps...
1). Run ng build --prod (If you get budgets error than increase the budget in angular.json file according to the error)
2). After above command, a dist folder will be generated containing your project folder, move this project folder which is present inside dist folder from angular project in to your node project say inside public folder (public/your_build_angular_project).
3). Now in your node main file say index.js or app.js, include these lines
const path = require('path');
app.use('/', express.static(path.join(__dirname, 'public/your_build_angular_project')));
4). Now serve your node server then when you hit it, you will get your angular project running
Hope this will help you or somebody else! Thanks.
Sample angularjs app directory is here :
AngularApp->myApp->
AngularApp->myApp->controllers
AngularApp->myApp->views
AngularApp->myApp->services
AngularApp->myApp->app.js
AngularApp->myApp->index.html
Create a package.json file and insert below code in it:
(Location : AngularApp->package.json)
{
"name": "myApp",
"version": "0.0.1",
"description": "My Project",
"dependencies": {
"express": "*"
},
"engine": "node >=0.6.x",
"scripts": {
"start": "node server.js"
},
"main": "server.js",
"repository": {
"type": "git",
"url": ""
},
"author": "myApp",
"license": "myApp",
"bugs": {
"url": ""
},
"homepage": "/"
}
Create server.js:
(Location: AngularApp->server.js )
var express = require('express');
var app = express();
app.use(express.static("myApp")); // myApp will be the same folder name.
app.get('/', function (req, res,next) {
res.redirect('/');
});
app.listen(8080, 'localhost');
console.log("MyProject Server is Listening on port 8080");
Run commnad 'npm install' after navigating to package.json file.
Run command 'npm start'. Open a browser and hit localhost:8080/

Resources