JSON file accessible without module exports

Viewed 121

In one tutorial, the author said the "require" function can execute other files but it doesn't have access to other file's function and variable Unless they are exported by using module exports.

but if the file is JSON, it is exported default. Other files have access without module exports. Why?

For example,

index.js

let app = require('./app');
let greetings = require('./greetings.json');
console.log('greetings', greetings); // Won't throw error
app.greet(); // throw Error

app.js

    function greet() {
       console.log('hello')
    }
    greet()

greetings.json

{
   english: "Hello",
   spanish: "Hola"
}
2 Answers

It seems you are calling the function greet in the app.js not exporting it, as such you can not access the method. You have loaded the app file but did not tell the modules what can be accessed from it. The file on the other side is loaded as a whole.

so if you would export the greet function as default or a part of the modules

module.exports = greet

that would make it available for calling.

This is how the CommonJS modules are working. You have to specify what you want to be a public of your module. Rest of it you might want to be private, not visible outside. I think this is good architectural decision to make all private except things you want to be private. That makes the code more safe.

But the JSON you gave, it is the representation of the data, so why you would like it to have private / public parts?

Related