How to export a variable \ array \ function?

Viewed 163

Fetching an array of users with jsonplaseholder. This array must be exported to another file and there already get what you need from the array (the name property of each of the users). I encounter the fact that the .map () method is not a function

get data:

const fetch = require("node-fetch");

let getMain = new Promise(async function (resolve, reject) {
    let response = await fetch('https://jsonplaceholder.typicode.com/users');
    resolve(response.json());
    reject();
});

getMain.then(mainData => {
    let dataLength = mainData.map(item => item.name.length);
    //console.log(dataLength, mainData);
    return Promise.resolve(dataLength)
})

    .catch(function (err) {
        console.log(err)
    });
//console.log(getMain);
function optionForPie(array) {
    return  array.map(item => item.name.length);
}

export let dataLength = optionForPie(getMain);
    console.log(dataLength);

error:

export let dataLength = optionForPie(getMain);
^^^^^^

SyntaxError: Unexpected token 'export'
?[90m    at Module._compile (internal/modules/cjs/loader.js:895:18)?[39m
?[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:815:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:727:14)?[39m
?[90m    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)?[39m
?[90m    at internal/main/run_main_module.js:17:11?[39m
1 Answers

In order to use ES6 Module syntax, you have to install babel npm package to transpile your ES6 to a commonjs target.

If you don't install babel, you have to use module.exports.

Related