Unable to start server on nodejs - node.js

I'm getting an error from command when I tried to run node server.js from my plesk node command.
I got the below error from the command:
> mongochat#1.0.0 start /var/www/vhosts/domain.win/console
> node server.js
events.js:165
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::4000
at Server.setupListenHandle [as _listen2] (net.js:1345:14)
at listenInCluster (net.js:1386:12)
at Server.listen (net.js:1474:7)
at Server.listen.Server.attach (/var/www/vhosts/domain.win/console/node_modules/socket.io/lib/index.js:273:9)
at new Server (/var/www/vhosts/domain.win/console/node_modules/socket.io/lib/index.js:59:17)
at Function.Server [as listen] (/var/www/vhosts/domain.win/console/node_modules/socket.io/lib/index.js:44:41)
at Object.<anonymous> (/var/www/vhosts/domain.win/console/server.js:2:37)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
Emitted 'error' event at:
at emitErrorNT (net.js:1365:8)
at process._tickCallback (internal/process/next_tick.js:114:19)
at Function.Module.runMain (module.js:692:11)
at startup (bootstrap_node.js:194:16)
at bootstrap_node.js:666:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! mongochat#1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the mongochat#1.0.0 start 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! /var/www/vhosts/domain.win/.npm/_logs/2018-08-18T09_01_29_349Z-debug.log
While gotten the below from 2018-08-18T09_01_29_349Z-debug.log
0 info it worked if it ends with ok
1 verbose cli [ '/opt/plesk/node/9/bin/node',
1 verbose cli '/opt/plesk/node/9/bin/npm',
1 verbose cli 'run',
1 verbose cli 'start' ]
2 info using npm#5.6.0
3 info using node#v9.10.1
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle mongochat#1.0.0~prestart: mongochat#1.0.0
6 info lifecycle mongochat#1.0.0~start: mongochat#1.0.0
7 verbose lifecycle mongochat#1.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle mongochat#1.0.0~start: PATH: /opt/plesk/node/9/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/var/www/vhosts/domain.win/console/node_modules/.bin:/opt/plesk/node/9/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
9 verbose lifecycle mongochat#1.0.0~start: CWD: /var/www/vhosts/domain.win/console
10 silly lifecycle mongochat#1.0.0~start: Args: [ '-c', 'node server.js' ]
11 silly lifecycle mongochat#1.0.0~start: Returned: code: 1 signal: null
12 info lifecycle mongochat#1.0.0~start: Failed to exec start script
13 verbose stack Error: mongochat#1.0.0 start: `node server.js`
13 verbose stack Exit status 1
13 verbose stack at EventEmitter.<anonymous> (/opt/plesk/node/9/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:285:16)
13 verbose stack at EventEmitter.emit (events.js:180:13)
13 verbose stack at ChildProcess.<anonymous> (/opt/plesk/node/9/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:180:13)
13 verbose stack at maybeClose (internal/child_process.js:936:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
14 verbose pkgid mongochat#1.0.0
15 verbose cwd /var/www/vhosts/domain.win/console
16 verbose Linux 3.10.0-862.3.3.el7.x86_64
17 verbose argv "/opt/plesk/node/9/bin/node" "/opt/plesk/node/9/bin/npm" "run" "start"
18 verbose node v9.10.1
19 verbose npm v5.6.0
20 error code ELIFECYCLE
21 error errno 1
22 error mongochat#1.0.0 start: `node server.js`
22 error Exit status 1
23 error Failed at the mongochat#1.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
This the simple server.js
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(4000).sockets;
// Connect to mongo
mongo.connect('mongodb://***:***#ds121382.mlab.com:21382/db', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('output', res);
});
// Handle input events
socket.on('input', function(data){
let name = data.name;
let message = data.message;
// Check for name and message
if(name == '' || message == ''){
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({name: name, message: message}, function(){
client.emit('output', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});
});
The package.json
{
"name": "mongochat",
"version": "1.0.0",
"description": "Simple chat app using sockets",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"mongodb": "^2.2.30",
"socket.io": "^2.0.3"
}
}

It is possible that another server is already running on port 4000. Try another port or turn off the already running server.

Related

spawn cd ENOENT

I am building a command line package.
I am using the spawn method to execute cd command.
Here's the code:
const cdChild = spawn('cd', [projectName])
cdChild.stdout.on('data', (data) => {
console.log(data.toString())
})
cdChild.on('error', (err) => {
console.log(err)
})
It gives the following error:
Error: spawn cd ENOENT
at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
at onErrorNT (node:internal/child_process:477:16)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4058,
code: 'ENOENT',
syscall: 'spawn cd',
path: 'cd',
spawnargs: [ 'bruh' ]
}
OS: Windows 10 21H1
Node: v16.13.0

What does error code 255 mean in Node.js child_process

I am running php command from Node.js child_process.
In response it is showing error and throwing error with error code 255 because of which my script is breaking.
When i execute the command from terminal it works fine but in child_process it gives error.
async function decrypt(cipher){
try {
var terminal = require('child_process');
var util = require('util');
var exec = util.promisify(terminal.exec);
var command = "usr/bin/php " + basePath + "/decrypt.php '" + cipher +"'";
return await exec(command);
}catch(err){
console.log(err);
console.error(err.code +' | '+ err.message);
}
}
module.exports = {
decrypt : decrypt
}
{ Error: Command failed: /usr/bin/php /var/www/html/nodejs/decrypt.php 'w5oFS8U4NGrleFHtptkmO+luDMw0z+fYrJ/onlj6fndIS/0QrWzOAsTN450VLZwR+GmDkyylybGJXUnx2VdeJQ=='
at ChildProcess.exithandler (child_process.js:281:12)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at maybeClose (internal/child_process.js:915:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
killed: false,
code: 255,
signal: null,
cmd: '/usr/bin/php /var/www/html/nodejs/decrypt.php \'w5oFS8U4NGrleFHtptkmO+luDMw0z+fYrJ/onlj6fndIS/0QrWzOAsTN450VLZwR+GmDkyylybGJXUnx2VdeJQ==\'',
stdout: '\t\n\n{"error":false,"decryptedText":"0324"}',
stderr: '' }
Desired Output is : '{"error":false,"decryptedText":"0324"}'
The error trace stack is more important than the error code.
process exit code

npm start command give ELIFECYCLE error with errno 1

I've run npm install on mac using sudo and it installed with 0 vulnerabilities.
When I give npm start, I'm getting error code ELIFECYCLE with errno 1.
I'm able to run the same in windows without getting an error.
Below is the log of the run
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm#6.4.1
3 info using node#v11.3.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle tanaaz#0.1.0~prestart: tanaaz#0.1.0
6 info lifecycle tanaaz#0.1.0~start: tanaaz#0.1.0
7 verbose lifecycle tanaaz#0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle tanaaz#0.1.0~start: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Files/Taannaz/Taannaz Web/tanaaz-master/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
9 verbose lifecycle tanaaz#0.1.0~start: CWD: /Files/Taannaz/Taannaz Web/tanaaz-master
10 silly lifecycle tanaaz#0.1.0~start: Args: [ '-c', 'node scripts/start.js' ]
11 silly lifecycle tanaaz#0.1.0~start: Returned: code: 1 signal: null
12 info lifecycle tanaaz#0.1.0~start: Failed to exec start script
13 verbose stack Error: tanaaz#0.1.0 start: `node scripts/start.js`
13 verbose stack Exit status 1
13 verbose stack at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack at EventEmitter.emit (events.js:182:13)
13 verbose stack at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:182:13)
13 verbose stack at maybeClose (internal/child_process.js:978:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid tanaaz#0.1.0
15 verbose cwd /Files/Taannaz/Taannaz Web/tanaaz-master
16 verbose Darwin 18.2.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
18 verbose node v11.3.0
19 verbose npm v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error tanaaz#0.1.0 start: `node scripts/start.js`
22 error Exit status 1
23 error Failed at the tanaaz#0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
Pls suggest the necessary.
I am sharing the lines in start.js as well below. Again this works completely fine in Windows 10 and throws me the error mentioned in MacOS Mojave
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(`Learn more here: ${chalk.yellow('https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#advanced-configuration')}`);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
you see the following
20 error code ELIFECYCLE
21 error errno 1
22 error tanaaz#0.1.0 start: `node scripts/start.js`
22 error Exit status 1
when the start.js reaches process.exit(1). if this is not expected, you should debug your code and fix that.

python-shell from a node application

Question:
How do I run my python script in my node app?
This works:
From command line, I run this, and it works.
python generatePersonTerraform.py -s http://localhost:8080/api/person/239/exportPersonGeneration
Code that does not work in Node server.js
var PythonShell = require('python-shell');
...
var runPythonRoutine = function (request, response) {
var PythonShell = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: ['-s'],
scriptPath: '.',
args: ['http://localhost:8080/api/person/135/exportPersonGeneration']
};
PythonShell.run('generatePersonTerraform.py', options, function (err, results) {
console.log(err);
});
}
Error:
at PythonShell.parseError (/root/my-app/node_modules/python-shell/index.js:191:17)
at terminateIfNeeded (/root/my-app/node_modules/python-shell/index.js:98:28)
at ChildProcess.<anonymous> (/root/my-app/node_modules/python-shell/index.js:89:9)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:194:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
executable: 'python',
options: [ '-s' ],
script: 'generatePersonTerraform.py',
args: [ 'http://localhost:8080/api/person/239/exportPersonGeneration' ],
exitCode: 1 }
Note
I have been trying to use https://www.npmjs.com/package/python-shell
EDIT 1
I changed the options to:
var options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: [],
scriptPath: '.',
args: ['-s', 'http://localhost:8080/api/serviceType/135/exportPluginGeneration']
};
and got this error:
at PythonShell.parseError (/root/my-app/node_modules/python-shell/index.js:191:17)
at terminateIfNeeded (/root/my-app/node_modules/python-shell/index.js:98:28)
at ChildProcess.<anonymous> (/root/my-app/node_modules/python-shell/index.js:89:9)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:194:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
executable: 'python',
options: null,
script: 'generatePersonTerraform.py',
args:
[ '-s',
'http://localhost:8080/api/person/135/exportPersonGeneration' ],
exitCode: 0 }
But, it also ran and worked, it just stalls the node app. So, if I figure out how to make it not stall then I am all good. The python script seems to build all the files it is supposed to.
'-s' should be in args, not pythonOptions.

Forever-monitor throwing ENOENT and not working

so I have:
var forever = require('forever-monitor');
var Monitor = forever.Monitor;
var child = new Monitor('clusters.js', {
max: 10,
silent: false,
killTree: true,
logFile: './logs/forever.log',
outFile: './logs/app.log',
errFile: './logs/error.log'
});
child.on('exit', function (err) {
console.log('Server exitted');
});
child.start();
and it always throw the same error: events.js:72 throw er; // Unhandled 'error' event with:
Error: spawn ENOENT
at errnoException (child_process.js:980:11)
at Process.ChildProcess._handle.onexit (child_process.js:771:34)
npm ERR! weird error 8
npm ERR! not ok code 0
Does anyone know what is going on and how to fix it?
Im on Windows 7 with:
"express": "3.3.5",
"forever-monitor": "~1.2.2"
https://github.com/blai/grunt-express/issues/12
Apparently the problem is with forever-monitor 1.2, I downgraded to 1.1 and it just worked.
From what I got there they dont seem to be doing anything about it either...

Resources