20
loading...
This website collects cookies to deliver better user experience
mkdir learn-express
cd learn-express
npm init -y
command to create a package.json
file for your application in the same directory.npm init -y
package.json
file , you will see the defaults that you accepted, ending with the license.{
"name": "learn-express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Express
is not a native package to Node
, so it must be installed. Because you want to ensure it's included in your node modules, make sure to install it locally and then require it in your server.Express
in the learn-express directory by running the command npm install express
in command prompt:npm install express
package.json
will now appear at the end of the package.json
file and will include Express
.{
"name": "learn-express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
main.js
.const express = require('express');
const app = express();
const port =process.env.port || 8000;
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`App listening on port ${port}!`)
});
const yourModule = require( "your_module_name" );
express
is the module's name, as well as the name we usually assign to the variable we use to refer to the module's main function in code like the one you mentioned.require
function, whose job is to load modules and give you access to their exports.var myvariable = require('express');
myvariable
instead, but convention is that you'd use the module's name, or if only using one part of a module, to use the name of that part as defined by the module's documentation.Express's
default export is a little unique in that it's a function with properties that are themselves functions (methods). This is absolutely acceptable in JavaScript, but not so much in other languages. That's why, in addition to using express() to build an Application
object, you can also use express.static(/*...*/)
to set up serving static files.The backticks in the `App listening on port ${port}!` let us interpolate the value of $port into the string.
>node main
App listening on port 8000