Anonymous
Anonymous

Reputation: 65

What is the Node.js equivalent of a PHP include?

I'm looking for a simple solution for server side includes of regular HTML and CSS (for repeated components like headers, footers, navigation, etc) that doesn't require extensive frameworks.

Upvotes: 5

Views: 4264

Answers (4)

Alfred
Alfred

Reputation: 51

In node js to include repetitive files like headers, footers etc. you will need a templating language such as ejs.

Using ejs here is a sample code snippet with the include tag

<%- include('./path/to/your/html/file') %>

Upvotes: 1

Mike
Mike

Reputation: 111

I think you like require "view components". Exists multiple view engines for nodejs, for example pug , or ejs. In this case, you use include

Upvotes: 0

hcs
hcs

Reputation: 319

You're looking for the

require()

function. Check out the documentation for this and other Node.js things here

If you want to use newer import statement, you may do so; it's not yet fully implemented in Node, but you can use it by using the .mjs extension on the file you need to import and then using the following command:

node --experimental-modules someFile.mjs

Upvotes: 0

Get Off My Lawn
Get Off My Lawn

Reputation: 36341

You can use require to require multiple files. However, since node caches the files, you will need to delete them from the cache if you want to used an un-cached version of the file.

index.js

app.get('/path', (req, res) => {
  clear()
  let headers1 = require('/headers/a.js')
  let headers2 = require('/headers/b.js')
  res.set(headers1)
  res.set(headers2)
})

// Remove from require cache
function clear() {
  delete require.cache[require.resolve('/headers/a.js')]
  delete require.cache[require.resolve('/headers/b.js')]
}

headers/a.js

module.exports = {
  'Content-Type': 'application/json'
}

headers/b.js

module.exports = {
  'Custom-Header': 'Brass Monkey'
}

Upvotes: 1

Related Questions