hello, im working on this code hereconst teams = [ { team: 'Arsenal', id: 'ars', address: 'https://www.marca.com/en/football/arsenal.html', base: '' }, { team: 'CF Chelsea', id: 'chl', address: 'https://www.marca.com/en/football/chelsea.html', base: '' }, { team: 'Liverpool', id: 'lvr', address: 'https://www.marca.com/en/football/liverpool.html', base: '' }, { team: 'Manchester City', id: 'mnc', address: 'https://www.marca.com/en/football/manchester-city.html', base: '' }, { team: 'Manchester United', id: 'mnu', address: 'https://www.marca.com/en/football/manchester-united.html', 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 => team.id == teamId)[0].address
const teamBase = teams.filter(team => team.id == teamId)[0].base
const teamName = teams.filter(team => team.id == 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 => team.id === 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