29
loading...
This website collects cookies to deliver better user experience
fs
module. If you don't have it installed, you can install by run this command:npm install fs
index.js
, and fill with this code:// Adding required module
const http = require('http');
const fs = require('fs');
// For development, use 4040
const port = 4040
// Set limit
const limit = 10
// Run server
server = http.createServer(function (req, res) {
fs.readFile('counter.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
// Check if page view(s) is less than limit
if (limit > parseInt(data)) {
// If the page view(s) is less than limit
res.end(`Hey, this page view(s) is ${data}! Can this page reach ${limit} views?`);
} else {
// If the page view(s) is more or same than limit
res.end(`Hey, this page view(s) is ${data}! Yay, the page views is reach ${limit}!`);
}
// Add +1 to the counter file
fs.writeFile('counter.txt', parseInt(data) + 1, 'utf8', function (err) {
if (err) return console.log(err);
});
});
}).listen(port)
counter.txt
. You can fill it with 0
, or any number that you like.node index.js
glitch-hello-node
option). You can delete all the files, except package.json
and .env
. It's ok if you wan't to keep the file to.port
variable value (line 7) to this:process.env.PORT
const port = process.env.PORT
package.json
file. Maybe this is the hardest part from this tutorial. So, be careful. At first, we need to change the script, with our index.js
file. Replace "start": "node server.js"
with "start": "node index.js"
. After that, we need to add some module that we need. You can add it by simply click "Add package" buttonfs
package. 29