Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 10 Current »

A quick over of three ways to create a node.js application

Creating an Application Base

Method 1

Simply create your .js files and a launch.json file.

Run your scripts using node <file>.js

You might want to add a package.json file to ease the execution of your application.  A basic package.json file looks like this

package.json
{
  "name": "sample2",
  "version": "1.0.0",
  "description": "quick web demo",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "Selvyn",
  "license": "ISC"
}


Method 2

Use the npm init command.  It will create the package.json file for you after prompting you to answer a few questions.  You still need to create your basic .js files.


Method 3

Using the npm express-generator.

  1. Install express-generator using the command npm install -g express-generator
  2. Create an app using npm init
  3. Add express files to your project using the command npm install express --save


Adding files to the project

Add the following code to your default root file (normally index.js but could be any file you choose)

index.js
var express = require("express");
var app = express();

app.listen(3000, () => {
   console.log("Server running on port 3000");
});

When you run this app you will see the message "Cannot GET /".  If you check the developer's tools console output you will see the following error "GET http://localhost:3000/ 404 (Not Found).  You are seeing this message because you have not set up any event handlers (your application has no endpoints)

Important

If you want to use import * as module from "module_file" add 

{"type": "module" }

to you package.json file.

When you switch to modules, require(...) will not be usable.



  • No labels