How to use html page in node js development?

currently I have html page with styles , css , images and js files. … Can we plug existing html pages into node js app development ?

Now I’m thinking how the html pages can be fit into node js app development ? What is the proper way to add them and use them in node js environment ?

I need some pointer on this …what to look at for this ?

node js tutorials does not talk much about this .

You’ll probably want to use something like Express. This is a server-side framework, that helps organize your web application into an MVC-style architecture on the server side. It takes care of handling requests and responses and lets you use a number of libraries for your HTML templating.

If you’re interested in investing some time and effort in learning how to build apps with Node/Express, I’d recommend this video course by Wes bos (it isn’t free, but as a SitePoint Premium member, you get a discount).

Alternatively, look for an up-to-date beginners tutorial online.

You could take a look at this free course too. I’m currently working my way through it as a bit of a refresher and so far it seem reasonably well put together.

https://www.edx.org/course/introduction-node-js-microsoft-dev283x

I think what you’re looking for is a static file server; typically you’ll have a directory like /public where all your HTML, assets etc. reside, and which you serve if no other endpoint is matched. If you’re using express this is as simple as including the express.static middleware; a basic implementation might look like this:

const http = require('http')
const url = require('url')
const fs = require('fs')
const mime = require('mime-types')

const PUBLIC_DIR = './public'

const staticFileServer = http.createServer((req, res) => {
  const { pathname } = url.parse(req.url)
  const filePathname = PUBLIC_DIR + pathname

  // Check if the file exists in the public directory
  if (!fs.existsSync(filePathname)) {
    res.statusCode = 404
    res.end(`${pathname} not found!`)
    return
  }

  // Read the file
  fs.readFile(filePathname, (err, data) => {
    if (err) {
      res.statusCode = 500
      res.end(`Error reading ${pathname}`)
      return
    }

    // Look up the mime type (using an external library here)
    // https://www.npmjs.com/package/mime-types
    const type = mime.lookup(pathname)

    if (type) {
      res.setHeader('Content-type', type)
    }

    // Serve the file
    res.end(data)
  })
})

staticFileServer.listen(8000)
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.