Run this, and make sure you're using the latest version of Node
$ node -v
v8.9.1
$ mkdir node_js (you can name it whatever you want)
$ cd node_js
($ atom .)
Then install ejs, it will create the node_modules file.
$ npm install ejs
Create a server.js file, and write these code below.
server.js
var http = require("http"),
fs = require('fs'),
ejs = require('ejs'),
qs = require('querystring');
var server = http.createServer();
var template = fs.readFileSync(__dirname + '/public_html/todolist.ejs','utf-8');
var posts = [];
function renderForm(posts,response){
var data = ejs.render(template,{
posts: posts
});
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data);
response.end();
}
server.on('request',function(request, response) {
if(request.method === 'POST'){
request.data = "";
request.on("data",function(chunk){
request.data += chunk;
});
request.on("end",function(){
var query = qs.parse(request.data);
posts.push(query.name);
renderForm(posts,response);
});
} else{
renderForm(posts,response);
}
});
server.listen(8080);
console.log("Server is listening");
Create a public_html folder and a todolist.ejs file in it.
It should look like this.
todolist.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>To Do List</title>
</head>
<body>
<h1>To Do List</h1>
</br>
<form method="post">
<input type="text" name="name">
<input type="submit" value="add!">
<ul>
<% for (var i = 0; i < posts.length; i++){ %>
<li><%= posts[i] %></li>
<% } %>
</ul>
</body>
</html>
To run the server,
$ node server.js
Server is listening
Now you can access to http://localhost:8080/ to see your app!
This is from
https://dotinstall.com/lessons/basic_nodejs
Thank you! dotinstall!