Node.js - javascript calling functions from javascript file

ぐ巨炮叔叔 提交于 2020-01-16 15:51:26

问题


I am working on a Express/NodeJs project. I am new to Express/NodeJs, I am trying to import airportQuery.js into DistanceFormula.js. I am trying to directly import airportQuery.js from DistanceFormula.js. Im trying to call getAirports and return the answer to DistanceFormula.js. I not sure if I have to use the node routing or if i'm doing it correctly.

File Stucture: File Structure

DistanceFormula.JS

import {getAirports} from "./api/airportQuery";
console.log(getAirports('3c675a'));

AirportQuery.js

async function getAirports(planeIcao) {
        let airport = {
            arrival: "",
            destination: ""
        };
        const airport_url = 'https://opensky-network.org/api/flights/aircraft?icao24=' + planeIcao + '&begin=1517184000&end=1517270400';
        const response = await fetch(airport_url);
        const data = await response.json();
        console.log(data[0]);
        console.log(data[0].estArrivalAirport);
        airport.arrival = data[0].estArrivalAirport;
        console.log(data[0].estDepartureAirport);
        airport.destination = data[0].estDepartureAirport;
        return airport
    }
const fetch = require("node-fetch");

export {getAirports};

ERROR: Uncaught SyntaxError: Cannot use import statement outside a module


回答1:


To use modules in node.js, you have to do the following:

  1. Be running a version of nodejs that supports ESM modules (v8.5+).
  2. Run with this command line flag: node --experimental-modules
  3. Name your file with an .mjs file extension OR specify it as a module in package.json

See the relevant documentation for more info.

This is true not only for the top level file you import, but if it also uses import, then the same rules above have to apply to it too.


Note, that once you get your modules to load properly, you will then have a problem with this line of code because getAirports() returns promise, not a value. All async functions return a promise, always. The return value in the function will become the resolved value of the returned promise. That's how async functions work. So, change this:

console.log(getAirports('3c675a'));

To this:

getAirports('3c675a').then(result=> {
    console.log(result);
}).catch(err => {
    console.log(err);
});


来源:https://stackoverflow.com/questions/58775491/node-js-javascript-calling-functions-from-javascript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!