Green Juzzy
Green Juzzy

Reputation: 45

fs writes file in wrong location

Im trying to use writefile, but for some reason it does it outside of ./events folder..

im trying to use fs like,

        fs.writeFile("./level.json", JSON.stringify(storage), (err) => {
            console.log(err)
        })

xp.js is trying to write the level.json in the same folder.

The files being used.

Upvotes: 0

Views: 281

Answers (2)

To be more consistent across different architectures I suggest you to use path module. So in your case:

fs.writeFile(require('path').resolve('events', 'level.json'), JSON.stringify(storage), (err) => {
  console.log(err)
});

Upvotes: 0

Chris Sandvik
Chris Sandvik

Reputation: 1927

This happens because ./ references the current working directory, so wherever you ran the script from. If you'd like the path to reference the same folder where the currently running js file is, use __dirname instead like so:

fs.writeFile(`${__dirname}/level.json`, JSON.stringify(storage), (err) => {
  console.log(err)
})

Source: https://www.geeksforgeeks.org/difference-between-__dirname-and-in-node-js/#:~:text=The%20__dirname%20in%20a,It%20works%20similar%20to%20process.

Upvotes: 2

Related Questions