LoginSignup
0
1

More than 5 years have passed since last update.

❄️JavaScript Very Simple "To Do List"

Last updated at Posted at 2017-11-21

スクリーンショット 2017-11-21 19.30.12.png


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.

スクリーンショット 2017-11-21 19.18.32.png

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:heart_eyes:!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1