Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

javascript - ECMAscript export in Node.js

Im creating an NFL football simulator in nodejs and am having trouble exporting one of my variables. As you can see in my get_teams.js i make many HTTP requests. I then process the responseArr and format the data. Where I am running into an issue is when I try and export the sorted_teams_array. you can find this code at the very bottom of get_teams.js.

I then try and import this array into tester.js and console log it. I will eventually use this file to inject a mongo database with the array, but for now am just trying to console log it and cannot get it to work. I am using the --experimental-modules in my npm scripts when I run npm run tester, and still nothing. Any help would be great! I am a noobie so please no hate!

get_teams.js

import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js';
import Defensive_stats from '../models/defensiveStatsModel.js';
import Game_stats from '../models/gameStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();

const teams = {};



function get_teams() {
  axios.all([
    axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/${process.env.SEASON}?key=${process.env.API_KEY}`),

    // ... many more gets

  ])
  .then(function (responseArr) {
      
    responseArr[0].data.forEach(element => {
        teams[element.Team] = new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
          element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
          element.PointsFor, element.PointsAgainst)
    });

    // many more forEach blocks on responseArr[1, 2, 3...]
    
    /* power rating algorithm logic
    _____________________________________________ */
    
   const teams_array = Object.entries(teams);

   export const sorted_teams_array = teams_array.sort((a, b) => {
      if (a[1].average_victory_margin > b[1].average_victory_margin) return -1;
      if (a[1].average_victory_margin < b[1].average_victory_margin) return 1;
      return 0;
    })

    console.log(sorted_teams_array);

    teams_array.forEach(element => {
      console.log(`average victory margin for ${element[0]} = ${element[1].average_victory_margin}`)
    });  

  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
}


get_teams();

tester.js

import { sorted_teams_array } from './get_teams';

console.log(sorted_teams_array);


/// returns
(node:58769) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:61
  let url = moduleWrapResolve(specifier, parentURL);
            ^

Error: Cannot find module /Users/jojovera/Documents/nflSIMULATION/teams/get_teams imported from /Users/jojovera/Documents/nflSIMULATION/teams/tester.js
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
    at Loader.resolve (internal/modules/esm/loader.js:94:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:240:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

package.json

{
  "name": "optionsscript",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node --experimental-modules app.js",
    "afc_west": "node --experimental-modules ../nflSIMULATION/teams/afc_west.js",
    "get_teams": "node --experimental-modules ../nflSIMULATION/teams/get_teams.js",
    "tester": "node --experimental-modules ../nflSIMULATION/teams/tester.js",
    "get_offensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_offensive_stats.js",
    "get_defensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_defensive_stats.js",
    "get_victory_margin": "node --experimental-modules ../nflSIMULATION/teams/get_victory_margin.js",
    "power_rank": "node --experimental-modules ../nflSIMULATION/teams/power_rank.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.0",
    "cheerio": "^1.0.0-rc.5",
    "colors": "^1.4.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "nodemon": "^2.0.6",
    "stats-lite": "^2.2.0",
    "terminal-kit": "^1.44.0",
    "tofixed": "^1.0.0"
  }
}

question from:https://stackoverflow.com/questions/65837959/ecmascript-export-in-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As addressed in the comments and chat, there were two issues: ESM isn't supported in Node 12, so an update to 15 fixed that. The other issue is that nothing was validly exported from get_teams: import and export are top-level keywords, and the export was taking place inside a .then. These minor changes allow the function to be imported and its result used in the tests:

export function get_teams() {
  return axios.all([
    /// rest of code

      return sorted_teams_array;
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
}

Usage example:

import { get_teams } from './get_teams'

get_teams.then((teams) => {
  teams.forEach(console.log)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...