How to import a file contains a list to my index.js? – JavaScript – SitePoint Forums

hello, im working on this code here
const teams = [ { team: 'Arsenal', id: 'ars', address: '', base: '' }, { team: 'CF Chelsea', id: 'chl', address: '', base: '' }, { team: 'Liverpool', id: 'lvr', address: '', base: '' }, { team: 'Manchester City', id: 'mnc', address: '', base: '' }, { team: 'Manchester United', id: 'mnu', address: '', base: '' } ]
this is a list of teams, the problem is that this is just a sample … the actual list have more than 100 teams. i want the create a “teamList.js” file and import it to my main file “index.js” because i want to make it well organized and not too long, then call it here …

app.get('/teams/:teamId', (req, res) => {
    const teamId = req.params.teamId
    const teamAddress = teams.filter(team => == teamId)[0].address
    const teamBase = teams.filter(team => == teamId)[0].base
    const teamName = teams.filter(team => == teamId)[0].team

how to do that? and i really appreciate it.

Hi @imadtupac82, you can just export the data like so:

export const teams = [/* ... */]

And then import it:

import { teams } from './teamsList.js'
app.get('/teams/:teamId', (req, res) => {
  const teamId = req.params.teamId
  const team = teams.find(team => === teamId)
  // ...

Note that in order to use ES6 imports in nodejs you have to add "type": "module" to your package.json, otherwise use require('./teamsList.js'). BTW if it’s just data it doesn’t have to be a JS file, a JSON file might be more appropriate I guess… or an actual database for that matter.

And you cannot mix ES6 with older code. So if you use module and import you cannot use require on other files

1 Like

Source link


Leave a Reply

Your email address will not be published. Required fields are marked *