Overview of the package.json file

The package.json file holds all of the information about the package we are trying to build. It even gives us the ability to tie it into our version control system, and we can even tie it into our build system. Let's go over this now.

First, a package.json file should have the following fields filled out:

There are many additional fields that can be used, as follows:

There are a few more fields that are located in the package.json file, but these are the most common ones.

One specific section of the package.json file that we want to look at is the scripts section. If we go to the website of npm, about the scripts section, it states the following:

The scripts property is a dictionary containing script commands that are run at various times in the life cycle of your package. The key is the life cycle event, and the value is the command to run at that point.

If we go to the more details section, we will see that there are life cycle hooks that we can use so that we have various scripts running through the bundling and distribution process.

It should be noted that this information is specific to Node Package Manager (npm). While learning about Node.js, we will come across npm quite a bit, so learning about Node.js has also meant learning about npm.

Some of the specific points that we are interested in are the prepare and install sections of the packaging life cycle. Let's see what these sections cover:

Another great thing about the scripts section is that we can put any arbitrary strings here and run npm run <script>. Whatever we decide to use as the value will be evaluated when we run the command. Let's add the following to our package.json file:

"config" : {
"port" : 8080,
"name" : "example",
"testdata" : {
"thing" : 5,
"other" : 10
}
},
"scripts" : {
"example-script" : "node main.js"
}

This will give us the ability to grab configuration data. On top of this, we have added a script that can be run with the npm run example-script command. If we create a main.js file and add the following fields to it, we should get the following output:

console.log(process.env.npm_package_config_port); //8080
console.log(process.env.npm_package_config_name); //'example'
console.log(process.env.npm_package_config_testdata); //undefined

This shows that we can put primitive values inside the configuration, but we can't try to access something that is a complex object. We can do the following to get to the properties of the testdata object:

console.log(process.env.npm_package_config_testdata_thing) //5
console.log(process.env.npm_package_config_testdata_other) //10

Now that we've gained some insight into the Node.js and npm ecosystems, let's take a look at how Node.js is put together and some of the key modules that we will be utilizing in the following chapters.