Basic steps for setting up a NodeJS application

Basic steps for setting up a NodeJS application

  1. Initial steps

    mkdir my-project
    cd my-project
    npm init -y
    

    By giving it the -y shorthand flag, you are telling npm that it should take all the defaults. If you leave the flag out, you are in charge to specify the information about your project manually.

    mkdir src
    cd src
    touch index.js
    console.log('Hello Project.');
    
  2. Running the code in the index file:

    From the project root folder, run this:

    node src/index.js
    
  3. Go to package.json and make this modification to scripts.

    "scripts": {
      "start": "node src/index.js",
      "test": "echo \"Error: no test specified\" && exit 1"
    }
    

    From now on, we can run npm start to run the code in src/index.js or

    "scripts": {
      "build": "node src/index.js"
    }
    

    From now on, we can run npm run build to run the code in src/index.js

  4. Add .gitignore file and add this to it: node_modules

  5. Using module system:

    In package.json, make this modification

    "type": "module"
    
  6. Adding additional functionality:

    If you add additional functionality using additional files, import them into the index file and run them

    import { convert } from './convert.js'
    
    console.log('Hello Project.');
    
    convert();
    

Links to this note