Show navigation

Today we get an introduction to server-side JavaScript, including creating a Node project, using npm to install 3rd-party dependencies, and creating scripts in the package.json file.

What your package.json file should look like at this point
{
  "name": "my-new-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

If you're reading older tutorials that work with Node, you'll likely see this older require() syntax for importing modules:

const { readFileSync } = require('fs');
const fileData = readFileSync('index.js', 'utf8');
console.log(fileData);

This known as 'CommonJS' syntax. CommonJS is a specification project started by Mozilla engineer Kevin Dangoor back in 2009, which introduced the idea of modules in JavaScript.

The CommonJS syntax above accomplishes the same thing as our import syntax, and it's pretty easy to translate one to the other if you're reading documentation or tutorials that are using the syntax that you're not using. To see how they compare, have a look at the code above, and compare it to the code we put into our read-stuff.js file.

The one thing to note is, to use the require() syntax, you have to remove this line from your package.json file:

"type": "module",

... meaning you can't use the import syntax anymore. You have to either use import or require(); you can't use both.

I've been showing you the `import/export` syntax, because it's part of vanilla JavaScript at this point, and all Node's documentation is written using this syntax at this point. CommonJS is likely on its way out.


Further Reading:


Further Reading:
Wait, I thought you said we could install multiple packages with a single command?

Yep, but only if they're the same type of dependency - either production or development. If you want to install some packages as dev dependencies, and some as production dependencies, you have to install them with separate commands.

That being said, you can concatenate commands with a double ampersand, and they'll be run one after the other. If you wanted to run both of the above commands with a single press of your enter key, you could write them like this:

npm install chart.js && npm install ‐‐save‐dev mocha
What your package.json file should look like at this point
{
  "name": "my-new-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chart.js": "^3.3.2"
  },
  "devDependencies": {
    "mocha": "^8.4.0"
  }
}

Table of ContentsJavaScript on the ServerNode PackagesnpmAnatomy of a package.json FileThe World's Simplest Static Site Generator