Node.js notes part 1
In nodejs, the global object is global
- DOM methods cannot be used
To clear
setInterval
1
2
3
4
5
6setTimeout(() => {
clearInteval(interval);
}, 3000);
const interval = setInterval(() => {
console.log('1s');
}, 1000);To get the dir and file path
1
2console.log(__dirname);
console.log(__filename);Modules & Require
1
2
3
4
5
6
7const requiring = require('./filename');
// return an empty object if the required file are not exporting things
// in the required file
const people = ['nina', 'gala'];
module.export = people;
// so that requring = ['nina', 'gala'];To export multiple things
1
2
3
4
5
6
7
8const people = ['nina', 'gala'];
const age = ['20', '45'];
module.exports = {
people: people, // or shortcut: people
age: age
// people, age for short
};Or destruct the exported object
1
2// in the requring file
const { people } = require('./people'); // same name required
The file system
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33const fs = require('fs');
// reading files
fs.readFile('./docs/hello.txt', (err, data) => { // (relativePath, function(ASYN))
if (err) { console.log(err); }
console.log(data.toString());
})
// For the execution order, while the file is reading, the code moves on
// writing files
fs.writeFile('./docs/target.txt', 'the text', () => { // ASYN
console.log('file was written')
})
// directories
if (!fs.existSync('./assets')) {
fs.mkdir('./assets', (err) => { // can't create an existing folder
if (err) {}
console.log('folder created');
})
} else {
fs.rmdir('', (err) => {
})
}
// deleting files
// to make sure the file exists
if (fs.existsSync('./file.txt')) {
fs.unlink('./file.txt', (err) => {
if (err){}
})
}Streams & Buffers
Streams - Start using data, before it has finished loading
Buffer - Chunks of data when data is streaming
1
2
3
4
5
6
7
8
9
10
11
12
13const fs = require('fs');
// read stream
const readStream = fs.createReadStream('some file', {encoding: 'utf8'});
// write stream
const writeStream = fs.createWriteStream('some file');
readStream.on('data', (chunk) => { // listen 'data' on the stream
console.log(chunk);
writeStream.write('---NEW CHUNK---');
writeStream.write(chunk);
})
// pipe: from a readable stream to a writable one
readStream.pipe(writeStream); // the same as above
Client & Servers - node create a server
1
2
3
4
5
6
7
8
9
10const http = require('http');
const server = http.createServer((req, res) => { // store it in case it will be used later
// respond to every request to the server
});
server.listen(3000, 'localhost', () => {
console.log('listening for requests on port 3000')
})Requests & Responses
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const server = http.createServer((req, res) => {
// set header content type
res.setHeader('Content-Type', 'text/plain');
// return a sentence to the browser
res.write('hello world');
res.end();
})
// send some HTML
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
// To add some styles
res.write('<head><link res="stylesheet" href="#"></head>')
res.write('<h1>Hello World</h1>');
res.write('<p>Hi Again</p>');
res.end();
})Use seperated HTML files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
// set header content type
fs.readFile('./dir/index.html', (err, data) => {
if (err) { // if error, keep the request hanging
console.log(err);
res.end(); // so end the request
} else {
res.write(data);
res.end();
// In short: res.end(data);
}
});
})Basic Routing
From above, for what route are being requested, we always get the same page. To send different HTML pages depending on different routes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
// To figure out the different routes
let path = './views/'; // the folder contains HTML pages
switch(req.url) {
case '/':
path += 'index.html';
break;
case '/about':
path+= 'about.html';
break;
default:
path += '404.html';
break;
}
// file operations ...
})
Status Codes
The type of response sent to the browser - How successful the request works
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17// 200 - fine
// 301 - Resource moved
// 404 - Not found
// 500 - Internal server error
switch(req.url) {
case '/':
path += 'index.html';
res.statusCode = 200;
break;
case '/about':
path+= 'about.html';
res.statusCode = 200;
break;
default:
path += '404.html';
res.statusCode = 404;
break;Redirect
1
2
3
4case '/about-old':
res.statusCode = 301;
res.setHeader('Location', '/about');
res.end();