Trying to run concurrently (npm ERR! code ELIFECYCLE npm ERR!) - node.js

I am trying to create a Full Stack Node & Vue application that takes data from an API. I am running into an issue where I am trying to run both the client and server concurrently but the code is running into an error. Please bear with me if I am structuring this question wrong as I am still fairly new to coding!
This is the following error log:
[0] Error occurred when executing command: npm run server
[0] Error: spawn cmd.exe ENOENT
[0] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[0] at onErrorNT (internal/child_process.js:469:16)
[0] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] Error occurred when executing command: npm run client
[1] Error: spawn cmd.exe ENOENT
[1] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[1] at onErrorNT (internal/child_process.js:469:16)
[1] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] npm run client exited with code -4058
[0] npm run server exited with code -4058
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! apex-tracker#1.0.0 dev: `concurrently "npm run server" "npm run client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the apex-tracker#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
From what I can tell the program is running fine up until it reaches the "dev" script in my package.json:
{
"name": "apex-tracker",
"version": "1.0.0",
"description": "Apex Legends user statistics tracker",
"main": "server.js",
"scripts": {
"start": "node server",
"server": "nodemon server",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Jared Mackay",
"license": "MIT",
"dependencies": {
"concurrently": "^5.0.1",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"morgan": "^1.9.1",
"node-fetch": "^2.6.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
prior to the errors, the program ran fine when I ran the npm run server command, however upon installing the client folder and adding the client and dev script that's when I ran into my errors.
Here is my server.js that I am trying to run with the client:
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
//Load configuration file
dotenv.config({ path: './config.env' })
const app = express();
//Develper logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
//Profile routes
app.use('/api/v1/profile', require('./routes/profile'));
const port=process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server running on ${process.env.NODE_ENV} mode on port ${port}`);
});
I've tried clearing the npm cache, deleting and reinstalling node-modules as well as package-lock.json, but this created more issues rather than fixing them. I had to revert back to an old git commit and now I'm stuck.
I don't think this route .js file is an issue but here it is just in case profile.js:
const express = require('express');
const router = express.Router();
const fetch = require('node-fetch');
router.get('/:platform/:gamertag', async (req, res) => {
try {
const headers = {
'TRN-Api-Key': process.env.TRACKER_API_KEY
}
const { platform, gamertag } = req.params;
const response = await fetch(
`${process.env.TRACKER_API_URL}/profile/${platform}/${gamertag}`,
{
headers
}
);
const data = await response.json();
if(data.errors && data.errors.length > 0) {
return res.status(404).json({
message: 'Profile Not Found'
});
}
res.json(data);
} catch (err) {
console.error(err);
res.status(500).json({
message: 'Server Error'
});
}
});
module.exports = router;
Thank you in advance!

spawn cmd.exe ENOENT
Your program does not know where to find cmd.exe.

Related

*ESLint Error* in React when trying to deploy Firebase Functions

Setting up a serverless backend using Firebase Functions. Tutorials I watched setting up the Functions folder all recommended using the ESLint feature to catch probable bugs and enforce style. POST lambda route notified a parsing error when locally deployed but everything still worked as needed. I go to deploy the backend to Firebase and I'm thrown a bunch of errors - thus not letting me continue. I go to the line it says I have an error, remove async await, the error goes away but the code breaks. What am I doing wrong? Is there still a way to deploy my code without having to delete the Functions folder and do it all over again?
index.js file within functions folder:
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
dotenv.config();
const stripe = require("stripe")(`${process.env.REACT_APP_STRIPE_SECRET_KEY}`);
// App config
const app = express();
// Middlewares
app.use(cors({origin: true}));
app.use(express.urlencoded({extended: true, useNewUrlParser: true}));
app.use(express.json());
// API routes
app.get("/", (req, res) => res.status(200).send("Hello World"));
// 👇 PARSING ERROR PREVENTING DEPLOY 👇
app.post("/payments/create", async (req, res) => {
const total = req.query.total;
console.log("Payment Request Received for: , total");
const paymentIntent = await stripe.paymentIntents.create({
amount: total, //sub-units of currency
currency: "USD",
});
res.status(201).send({
clientSecret: paymentIntent.client_secret,
})
});
// Listen command
exports.api = functions.https.onRequest(app);
.eslintrc.js file within functions folder:
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};
package.json file within functions folder:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "12"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0",
"stripe": "^8.137.0"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Errors in terminal when trying to deploy:
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/Desktop/coding-repos/ecommerce/client/functions
> eslint .
/Users/Desktop/coding-repos/ecommerce/client/functions/index.js
22:47 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/.npm/_logs/2021-03-05T22_26_21_954Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
In these situations, it is a good idea to read the stack trace. The error message points to the issue or what might be the issue that you can debug.
As you can see, the error location is around 22:47 here in your index.js file. Although this is not always precise, you can assume the error will be on that line or possibly above or below it. There are exceptions to this. For example, you might not have closed brackets elsewhere in the code.
/Users/Desktop/coding-repos/ecommerce/client/functions/index.js
22:47 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
Also, review the logs as they provide a lot of detailed information to identify what is happening. They can sometimes be hard to understand, but you usually find what you are looking for if you search backwards through the trace.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/.npm/_logs/2021-03-05T22_26_21_954Z-debug.log
A lot of developers will copy and paste code that they find on the internet. It is good when you need snippets when you are unsure how something works but can be a pain to debug because developers take old code and mix the versions up.
I am more familiar with Python, but my guess is ESlint is having problems with a version of Javascript. Look at this Stackoverflow question as I think it answers your issue. The solution appears to be using a parser.
"parser": "babel-eslint"

Problem when i run npm run dev in my node backend

I try to build API with node,and i have my frontend separated in folder called client,and this files(package.json,server.js is in my project root folder.
When i want to npm run dev,it gives me this error:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! clothing-server#1.0.0 dev: `concurrently --kill-others-on-fail "npm server" "npm client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the clothing-server#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Here is my server.js:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(port, error => {
if (error) throw error;
console.log(`Server running on ${port}`);
});
app.post('/payment', (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: 'usd'
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ error: stripeRes });
}
});
});
and my package.json:
{
"name": "clothing-server",
"version": "1.0.0",
"engines": {
"node": "10.16.0",
"npm": "6.9.0"
},
"scripts": {
"client": "cd client && npm start",
"server": "nodemon server.js",
"build": "cd client && npm run build",
"dev": "concurrently --kill-others-on-fail \"npm server\" \"npm client\"",
"start": "node server.js",
"heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "1.7.4",
"cors": "2.8.5",
"dotenv": "8.2.0",
"express": "^4.17.1",
"stripe": "8.6.0"
},
"devDependencies": {
"concurrently": "^5.0.2"
}
}
I try to delete my lock file and node_modules and npm cache clean ,but they don't help
In your package.json file, It should be
"dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""
Your npm run dev script calls npm server, which it tries to call nodemon server.js, but apparently the nodemon is not installed in your project. See your list of dependencies, and install nodemon, or remove it from server script.
Apparently it should work ;)

issue deploying node.js server to heroku

I am running into the error
An error occurred in the application and your page could not be served.
when running 'heroku open' command. On heroku dashboard it says deployed successfully but then it will not run 'it is working' from the app.get line of code.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'benjohnson',
password : '',
database : 'smart-brain'
}
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send('its working!') })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(process.env.PORT || 3000, ()=> {
console.log(`app is running on port ${process.env.PORT}`);
})
When running the server.js file within the heroku cli i receive the error, when running 'heroku logs --tail' i receive this error?
> node#1.0.0 start /Users/benjohnson/.Trash
> nodemon server.js
sh: nodemon: command not found
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! node#1.0.0 start: `nodemon server.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likel
y additional logging output above.
npm WARN Local package.json exists, but node_modules missing, di
d you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/benjohnson/.npm/_logs/2019-09-25T14_11_11_91
0Z-debug.log
The error is about nodemon.
Open the package.json, is at the same folder with server.js
Find:
"scripts": {
"start": " nodemon server.js",
},
And replace it with:
"scripts": {
"start": "node server.js",
"start:dev": "nodemon server.js"
},
Upload again in Heroku.
When you want to run the project locally, just run in your terminal npm start:dev and it will load server.js with nodemon.

How to build next.js production?

I try to get a production build in next.js to run it on my server but I can't build next.js production build when I try
npm run build
Does anyone know how to get a prod build in next.js working correctly I did everything in the next.js documentation but always get this error below. If I do a dev build it works just fine but trying prod build results in errors.
I did also next build many times and reinstalled all node_modules packages still having this error.
it always shows me in terminal
Error: Could not find a valid build in the '/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/.next' directory! Try building your app with 'next build' before starting the server.
at Server.readBuildId (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:753:15)
at new Server (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:80:25)
at module.exports (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next.js:6:10)
at Object.<anonymous> (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/next.config.js:6:13)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at loadConfig (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/config.js:47:28)
at _callee2$ (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/build/index.js:52:42)
at tryCatch (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:114:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello-next#1.0.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello-next#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/kk/.npm/_logs/2018-12-10T19_58_00_588Z-debug.log
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
next.config.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/projects/:page", (req, res) => {
const page = req.params.page;
let file = "";
switch (page) {
case "example1":
file = "/projects/example1";
break;
case "example2":
file = "/projects/example2";
break;
}
return app.render(req, res, file, { page });
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
package.json
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
If anyone has an idea would be so nice! I plan to run this next.js site using node on my AWS server. But to do this I need to get production build of react.js currently I can run just a development build.
Hope someone has an idea.
Thanks in advance!
next build followed by next start should be the right commands to prepare the build for production and run it.
Here's an example for package.json. if you want to export application to run as a static content, something like hosting it in s3 as a static website, you need to run next export
...
"scripts": {
"build": "next build",
"start": "next start",
"export": "next export"
}
...
Make sure you have the above scripts in your package.json then run the following in order
$ npm run build
$ npm run start
If you want to start application with specific port, you can specify -p port as argument for npm run command
npm run start -- -p 3232
If you want to incorporate this into a CI/CD pipeline, you need to have Dockerfile, here's a simple example
FROM node:alpine
#copy source
COPY . /app
# Install deps
RUN cd /app && npm install
# Build
RUN npm run build
ENTRYPOINT [ "npm", "run", "start" ]
Still need more explanation or help, don't hesitate to leave a comment and I will be more than happy to assist.
Seems your server.js config is not correct. Please try moving all you have from your next.config.js to server.js make sure the next.config.js file is empty then create a new npm run script:
"prod_start": "NODE_ENV=production node server.js"
Your package.json should then look like this:
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"prod_start": "NODE_ENV=production node server.js",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
make sure to run: npm run build && npm run prod_start
Then you should have a production build of react running using next.js
Let me know if you got question.
You must launch next build at your root folder and not inside .next/
There are 3 ways todo it:-
way 1: use next build instead of npm run build
way 2: npm run build npm install -g serve serve -s build
more info: https://create-react-app.dev/docs/deployment/
way 3: after npm run build, Remove / from JS,CSS links from /static/index.html file. eg. replace these 2 lines
<script defer="defer" src="/static/js/main.aa87bc08.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet"/>
with these 2 lines
<script defer="defer" src="static/js/main.aa87bc08.js"></script>
<link href="static/css/main.073c9b0a.css" rel="stylesheet" />
now it even work on file:///D:/codes/ProjectName/build/index.html
tell me in the comments if none of the 3 ways work, I'll find, try & tell way 4, 5, etc.

npm error ELIFECYCLE on ctrl+c

I've started a new socket.io project with heroku. The server runs fine locally on windows. I start it with npm start but when I shut it down with ctrl + c I get this error in the console:
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.4
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! test1#1.0.0 start: `node index.js`
npm ERR! Exit status 3221225786
npm ERR!
npm ERR! Failed at the test1#1.0.0 start script 'node index.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the test1 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node index.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs test1
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls test1
npm ERR! There is likely additional logging output above.
I have searched for a solution but the very little I have been able to find has given no solution. I've tried updating npm and node, running npm install again, clearing the npm cache and probably some other actions I can't recall.
Here is my index.js
const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
const PORT = process.env.PORT || 3000;
const server = express()
.use(express.static(__dirname + '/client'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const io = socketIO(server);
const pg = require('pg');
var connectionString = "postgres://jdirjtnfueksiw:823e80fbae9599f0d6797f82342d83bccf1caea764b8a1659356f3ee89r69f94#ec1-78-222-138-451.compute-1.amazonaws.com:5432/jf84jd75jgu26d5?ssl=true";
pg.connect(connectionString, function(err, client, done) {
if (err) {
throw err;
}
else {
console.log('Database connection test successful');
}
});
io.on('connection', function (socket) {
socket.emit('connected');
console.log('New connection from ' + socket.request.connection.remoteAddress);
socket.on('disconnect', function () {
console.log('Player left');
});
});
my package.json
{
"name": "test1",
"version": "1.0.0",
"engines": {
"node": "6.11.4"
},
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"pg": "6.x",
"express": "4.13.4",
"socket.io": "1.4.6"
},
"devDependencies": {},
"description": ""
}
Thank you for any help.
In the index.js can you try putting the following code:
process.on('SIGINT', () => {
process.exit();
});
I think the issue is that Ctrl+C kills the application but there is still some process running in the background. This will ensure that it is terminated.
Hope this helps!

Resources