- Install node and npm. They are packaged together here.
- Open a terminal window and find the directory you want to work in.
- Run
npm initin that folder and answer the questions. This will create apackage.jsonfile. - Create an
index.jsfile. This is where we will start writing code!
You dont need a package.json file to run a node script. You can just create a script and run node script.js. However you need a package.json to install dependencies like third party libraries.
Lets make a simple API server!
- Install the third-party library "ExpressJS" which lets us run a node server.
- Run
npm install express. This will add Express to ourpackage.jsonfile and will include the library in thenode_modulesfile. - Inside our
index.jsfile include the following code:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})- Modify the
package.json'sscriptblock:
"scripts": {
"start": "node index.js"
},- Run
npm start. Alternatively you can just runnode index.js, but using thepackage.jsonis preferable. - Visit http://localhost:3000/ and see it in action!