Search code examples
javascriptnode.jsimportalpha-vantage

Import function in node module (alphavantage)


I'm trying to test out the alphavantage module in Node and it keeps throwing this error:

import Util from './lib/util';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1055:16)
    at Module._compile (internal/modules/cjs/loader.js:1103:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1159:10)
    at Module.load (internal/modules/cjs/loader.js:988:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1028:19)
    at Object.<anonymous> (C:\Users\thepa\Desktop\FANSchool\FANEconimics\app.js:1:15)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1159:10)

File structure:

"C:\Users\thepa\Desktop\FANEconimics\app.js"
"C:\Users\thepa\Desktop\FANEconimics\data.json"
"C:\Users\thepa\Desktop\FANEconimics\keys.txt"
"C:\Users\thepa\Desktop\FANEconimics\LICENSE"
"C:\Users\thepa\Desktop\FANEconimics\package.json"
"C:\Users\thepa\Desktop\FANEconimics\package-lock.json"
"C:\Users\thepa\Desktop\FANEconimics\README.md"
"C:\Users\thepa\Desktop\FANEconimics.git"
"C:\Users\thepa\Desktop\FANEconimics\node_modules"
"C:\Users\thepa\Desktop\FANEconimics.gitignore"

app.js:

const alpha = require("alphavantage")({ key: 'mykey' });

alpha.data.intraday(`msft`).then(data => {
    console.log(data);
  });

It happens after I run node app.js. I saw that older versions of node don't support ESM imports, so I updated to the latest version v13.5.0. also updated npm to v6.13.4

Would this be a problem with the module or my setup?


Solution

  • Honestly, this is a mistake of the library. They are using experimental features without transpiling their code.

    My advice is not to use the node package and rather the REST API.

    Install fetch to easily consume the API:

    npm i --save node-fetch
    

    Then run something like this:

    const fetch = require("node-fetch")
    
    const base = "https://www.alphavantage.co/"
    
    const apikey = "demo"
    
    const query = (function_name, symbol, interval = "5min") => fetch(
        base + "/query?" + new URLSearchParams({ "function": function_name, symbol, interval, apikey })
    )
    
    
    query("TIME_SERIES_INTRADAY", "MSFT")
        .then(response => response.json())
        .then(data => {
            console.log(data)
        })