Creating a Node.js application
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
{ "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.
- Install express-generator using the command npm install -g express-generator
- Create an app using npm init
- 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)
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, see https://stackoverflow.com/questions/62488898/node-js-syntaxerror-cannot-use-import-statement-outside-a-module