I am working on CLI game with Node.js and I have an issue. I have to create a save game option and I am doing it by storing the data in a JSON file. However, it gets stored as undefined.
In stats.js
I am creating those values by calling a random
functions that I created:
//stats.js
export let playerHealthDisplay = randomHealth()
let stats = () => {
console.log("STATS")
let userStats = {
health: playerHealthDisplay,
strength: random(),
brains: random(),
money: 0,
xp: 0,
}
}
export let userStats
export default stats
In save.js
I created a function to save it in a JSON file:
//save.js
import { userStats } from "../utils/stats.js"
const save = async () => {
console.log(userStats) // undefined
const data = JSON.stringify(userStats)
writeFile("userStats.json", String(data), (err) => {
if (err) {
throw err
}
})
console.log("Thanks for playing. -- (game saved)")
}
This works half good. It does create a JSON file called userStats.json
(as it is supposed to) but it doesn't store the data correctly. It's stored undefined
. I did the console.log()
of imported userStats
to check wheter it's imported correctly and it returns undefined
.
So where did I go wrong ? Thanks in advance.