I have a relatively simple express setup along the lines of:
const app = express()
// ... some middleware registration
const server = app.listen(3000)
process.once('SIGINT', () => server.close())
I get an error: TypeError: server.close is not a function when nodemon restarts the process (I'm on windows, so I get SIGINT). I get the same error for closeAllConnections() for example.
What is the most puzzling is that some objects work as expected...
const server = ...
const socket = new WebSocket(...)
process.on('SIGINT', () => {
server.close() // dies
socket.send(...) // works
})
Does anyone have a clue what is going on with this combination of express/http, nodemon and javascript?
Related
const jsonServer = require('json-server')
const cors = require('cors')
const path = require('path')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(cors())
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.use(router)
const PORT = 8000
server.listen(PORT, () => {
console.log(`JSON Server is running on http://localhost:${PORT}`)
})
I am using cyclic.sh for deployment. How to solve this error?
I was trying to deploy a json-server. And while doing a post request I got this error.
Taking as a starting point that you shouldn't use a tool like json-server in production environments, I could understand you might be using it for demo purposes. That case, there are some serverless solutions which prevents your code from open files in write mode, so that's why the jsonServer.router(...) line fails its execution.
If you don't matter about that db.json file being updated by the requests (because anyway, your deployment solution doesn't seem to allow it), you could just use instead a js object, that can be modified in memory (but, of course, the json file will still keep intact). So, instead of:
const router = jsonServer.router(path.join(__dirname, 'db.json'))
try using something like:
const fs = require('fs')
const db = JSON.parse(fs.readFileSync(path.join(__dirname, 'db.json')))
const router = jsonServer.router(db)
I want to simulate a crash with Node.js by using process.kill. I did a basic app with express.js in terminal #1
app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hi!');
});
const server = app.listen(3000, () => console.log('Server ready'));
console.log(process.pid);
process.on('SIGINT', function () {
console.log('Simulate crash');
});
Then, I'm running in another terminal (terminal #2) a node file that kill the process of terminal #1
kill.js
const fs = require('fs');
const args = process.argv.slice(2)[0];
process.kill(args, 'SIGINT');
So when I run kill.js with the following command $ node kill.js YOURPROCESSPID in the terminal #2, it didn't print the "simulate crash" in the terminal #1. I'd like to know how to make this happen. Thank you.
I also added the console down here.
I need my server to go up, call a function then go down.
From what I've seen on the web I should use this section of code:
const express = require('express');
const app = express();
app.on('listening', () => {
console.log("Server up...");
console.log("Server going down...");
});
but for some reason this does not work for me.
The program does go up but the logs are not written.
const express = require("express");
const app = express();
const server = app.listen(3000);
//call whatever function you need here
server.close(() => console.log("Server going down..."));
First we start the server using app.listen and later when you want to close it just do server.close()
I have created windows service from nodeJs application using node-windows package. Below is my code.
Main.js
var Service = require('node-windows').Service;
// Create a new service object
var svc = new Service({
name:'SNMPCollector',
description: 'SNMP collector',
script: './app.js',
nodeOptions: [
'--harmony',
'--max_old_space_size=4096'
]
//, workingDirectory: '...'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
/* svc.uninstall(); */
App.js
const { workerData, parentPort, isMainThread, Worker } = require('worker_threads')
var NodesList = ["xxxxxxx", "xxxxxxx"]
module.exports.run = function (Nodes) {
if (isMainThread) {
while (Nodes.length > 0) {
// my logic
})
}
}
}
Now when I run main.js, it creates a windows service and I can see the service running in services.msc
But, how can I call this run() method which is inside the running service, from any outside application? I couldn't find any solution for this, any help would be great.
You might consider simply importing your run function where you need it and run it there, then there is no need for a windows service or main.js - this assumes that "any outside application" is a Node application.
In your other application you you do the folowing:
const app = require('<path to App.js>');
app.run(someNodes)
For broader usage or if you do need to run it as a service, you could be starting an express (or another webserver) in your App.js with an endpoint that invokes your run function. Then from anywhere else you'll need to make an http call to that endpoint.
App.js
const express = require('express')
const bodyParser = require('body-parser')
const { workerData, parentPort, isMainThread, Worker } = require('worker_threads')
const app = express()
const port = 3000
var NodesList = ["xxxxxxx", "xxxxxxx"]
const run = function (Nodes) {
if (isMainThread) {
while (Nodes.length > 0) {
// my logic
})
}
}
}
app.use(bodyParser.json())
app.post('/', (req, res) => res.send(run(req.body)))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
(Based off of example for express - https://expressjs.com/en/starter/hello-world.html)
You'll need to install both express and body-parser: $ npm install --save express body-parser from the directory of App.js.
From your other applications you will need to call the endpoint http://localhost:3000 with a POST request and the Nodes as a JSON array.
You can expose it on a port like the other answer mentions, though you'll want to make sure you don't expose it more broadly depending on the environment you're running in. There's a good answer here on ensuring the port is locked down.
As an alternative to exposing it on a port you can simply call the function by running the command in any other application:
node -e 'require("/somePathToYourJS/app").run()'
One concern is that app.js will now run at whatever permissions the calling application has. Although that can be resolved by running runas prior. More details here. But an example is:
runas /user:domainname\username "node -e 'require(^"/somePathToYourJS/app^").run()'"
I'm making a server with node.js, and I'm trying to add TensorFlow.js into it. I installed with npm, both the CPU and GPU versions, but when I include the library with require('#tensorflow/tfjs-node') or require('#tensorflow/tfjs-node-gpu'), it shows me an 'Illegal instruction' error. (Tell me if I misspelt something, I'm Spanish.)
I tried to reinstall both the CPU and GPU versions, but I don't know what to do.
This is the code I used:
let tf = require('#tensorflow/tfjs-node'); // The error is from this line
let argparse = require('argparse');
let express = require("express");
let app = express();
let server = app.listen(3000);
app.use(express.static("public"));
console.log("Server running!");
let socket = require("socket.io");
let io = socket(server);
io.sockets.on("connection", connectionListener);
...
It's supposed to show the 'Server running!' the message, but the only thing it shows is:
Instrucción ilegal (`core' generado)
Shows that because is in Spanish. In English is:
Illegal instruction (core dumped)