Reputation: 1
I'm working on a project in NodeJS that takes coords from a JSON data.json
and then uses that coords to bring the weather, and then that data of the weather, to write it into another JSON.
The issue here is that my function uses and wait fetch, and that gives me an error that says fetch is not defined so, I did what a question here said, I downloaded fetch, I imported it and now its says that I need to type
"type": "module"
in my package.json
, so I did and now it says that my var fs=require('fs'
is not defined :c I'm using filesystem to create that another JSON, any help is welcomed, thank you c: here's my app.js
var fs = require('fs')
import fetch from "node-fetch";
const api_key = '******'
async function calcWeather(){
const info = await fetch('./data.json') // fetch editable c:
.then(function(response) {
return response.json();
});
for (var i in info) {
const lat = info[i][0].latjson;
const long = info[i][0].lonjson;
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
fetch(base)
.then((responses) => {
return responses.json();
})
.then((data) => {
var myObject = {
Latitud: data.coord.lat,
Longitud: data.coord.lon,
Temperatura: data.main.temp,
Ciudad: data.name,
Humedad: data.main.humidity,
Descripcion: data.weather[0].description,
};
// convert JSON object to a string
const _myObject = JSON.stringify(myObject);
/* console.log(JSON.stringify(myObject)) */
// write file to disk
fs.writeFileSync('data2.json', _myObject, 'utf8', (err) => {
if (err) {
console.log(`Error writing file: ${err}`);
} else {
console.log(`File is written successfully!`);
}
});
fs.writeFile('data.txt', _myObject,'utf8', (err) => {
if (!err){
console.log(`Written succesfully! c:`)
}
})
});
}
};
calcWeather()
and here's my JSON
[
[
{
"latjson": 21.1524,
"lonjson": -101.7108
}
],
[
{
"latjson": 19.4328,
"lonjson": -99.1346
}
],
[
{
"latjson": 20.6605,
"lonjson": -103.3525
}
]
]
and here's my package.json c:
"name": "node-js-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"node-fetch": "^3.0.0"
}
}
Upvotes: 0
Views: 18422
Reputation: 2166
You can't import ES6 module in common.js
You have to rename your file to have a .mjs
You can create a file called insert_whatever_name_you_want.mjs
import fetch from 'node-fetch'
fetch('https://google.com')
.then(res => res.text())
.then(text => console.log(text))
Run it with node app.mjs
Further reading: https://techsparx.com/nodejs/esnext/esmodules-from-commonjs.html
Upvotes: 1