3

Learning Nodejs for my personal projects. Analysing other developers code examples, watching youtube videos. I noticed one thing that I don't understand completely, why most of nodejs examples I come across have a code part for http server initiation and port listening? But application itself not using any http related things like processing http requests/responses. For example:

const express = require('express')
const path = require('path')
const http = require('http')
const cors = require('cors')


const PORT = process.env.PORT || 5000
const app = express();
const server = http.createServer(app).listen(PORT, () => console.log(`Listening on ${PORT}\n`))
app.use(express.static(path.join(__dirname, 'public')))
app.use(cors({ credentials: true, origin: '*' }))

If my nodejs application is a script that needs to be run on server side that collects some information from other API's and stores in a database, etc., do I need to create and start HTTP server anyway?

2
  • No you don't have to put in place a server to respond to HTTP requests if you don't have any case for it. Commented Apr 29, 2022 at 8:56
  • You can run node scripts from the command line, so there is no need create/use a server to 'host' the script. If you are using NPM, see the scripts section of package.json to understand how this is done. Commented Apr 29, 2022 at 9:06

1 Answer 1

1

why most of nodejs examples I come across have a code part for http server initiation and port listening?

Because that's how people use nodejs most of the time: as a web server. Which doesn't mean it is mandatory or even a good practice.

do I need to create and start HTTP server anyway?

Of course not. Why would you do that if you don't need it? Do not worry about tutorials or examples, these don't know about your case and your needs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.