Skip to content

Node.js Streams

fs.createReadStream()

Task 1: Display the content of "file.txt" in the browser window.

//file.txt
line 0
line 1
line 2
line 3
line 4 
const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer((req, res) => {
    fs.readFile(path.join(__dirname, "file.txt"), "utf8", (err, data) => {
        if (err) throw err;
        res.writeHead(200, {"Content-Type": "text/plain"});
        res.end(data);
    });
});

server.listen(9000);

You can see the "file.txt" content is displayed in the browser window.

Task 2: Check the following code.

const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer((req, res) => {
    const stream = fs.createReadStream(path.join(__dirname, "file.txt"));
    stream.pipe(res);
});

server.listen(9000)

You can see the "file.txt" content is displayed in the browser window.

fs.createReadStream()

The fs.createReadStream() takes the filename as a parameter and reads the file in chunks.

pipe()

The pipe() method is called on the file stream. It takes the source and sends it to the destination. For example; the stream.pipe(response) method takes the file chunks and sends them as an HTTP response.

Why Streams?

The node.js streams are efficient in reading large files. Streams can save memory space and time.

Task 3: Create a stream to read the following "script.js" file, and display the result in the browser window.

// deal with buttons
let buttons = document.getElementsByClassName("container__buttons")[0];
let textarea = document.getElementById('container__textarea');
let wordsCount = buttons.addEventListener('click', function(e){
    e.preventDefault();
    let count = parseInt(e.target.id.split("-")[1]);
    let urlPortion = `/ajax`; 
    // launch ajax request
    let xhr = new XMLHttpRequest();
    xhr.responseType = 'json';
    xhr.open('POST', urlPortion , true);
    xhr.onload = function(){
        if(this.status === 200){
            textarea.textContent = '';
            textarea.textContent = xhr.response.text;
        }
    }
    xhr.onerror = function(){
        console.log("Some error occured")
    }
    //xhr.open("post", "");
    let data = {"count": count};
    xhr.send(JSON.stringify(data));
});

// deal with copy to clipboard button
let copyButtons = document.getElementsByClassName("container__button_copy");
for (copyButton of copyButtons){
    copyButton.addEventListener('click', function(e){
        e.preventDefault();
        textarea.select();
        textarea.setSelectionRange(0, 99999);
        document.execCommand("copy");
    });
}
const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer((req, res) => {
    const stream = fs.createReadStream(path.join(__dirname, "script.js"), "UTF-8");
    res.writeHead(200, {"Content-Type": "text/javascript"}); 
    stream.pipe(res);
});

server.listen(9000)

You can see the "script.js" content is displayed in the browser window.

Task 4: Create a stream to read the following "style.css" file, and display the result in the browser window.

html, body{
    height: 100%;
    background: #e1e1e1;
}

body{
    display: flex;
    flex-direction: column;
    align-items: center;
}

.container{
    height: 70%;
    margin: auto;
    display: flex;
    flex-direction: column;
    align-items: space-between;
}

.container__block{
    margin: 0.3rem;
    padding: 0.4rem;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.container__button_copy{
    display: block;
}

.container__buttons{
    display: flex;
    flex-direction: row;
    justify-content: center;
}

.container__button:hover{
    cursor: pointer;
    opacity: 0.8;
}

.container__button{
    outline : none;
    border: none;
    background: #001f3f;
    color: #fff;
    font-weight: bold;
    margin: 0 1rem;
    padding: 0.7rem;
    border-radius: 0.5rem 0;
}

.container__textarea{
    font-size: 1.2rem;
}

.container__button_copy{
    background: #2ECC40;
    margin: 0.5rem;
}
const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer((req, res) => {
    const stream = fs.createReadStream(path.join(__dirname, "style.css"), "UTF-8");
    res.writeHead(200, {"Content-Type": "text/css"}); 
    stream.pipe(res);
});

server.listen(9000)

You can see the "style.css" content is displayed in the browser window.

Mini Projects

Project 1

Task 5: Create a nodejs project that serves html, css, and javascript files. Hints: 1. you can use req.url.match("\.css$") to match any css file. 2. you can use req.url.match("\.js$") to match any javascript file.

Create this structrue for your project:

 ├─ public/
 │  ├─ css/
 │  │  ├─ style.css
 │  ├─ js/
 │  │  ├─ script.js
 │  ├─ index.html
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
    if(req.url === '/'){
        let indexPath = path.join(__dirname, "public", "index.html");
        let stream = fs.createReadStream(indexPath, "UTF-8");
        res.writeHead(200, {"Content-Type": "text/html"});
        stream.pipe(res);
    }else if(req.url.match("\.css$")){
        let cssPath = path.join(__dirname, "public/css", req.url);
        let stream = fs.createReadStream(cssPath, "UTF-8");
        res.writeHead(200, {"Content-Type": "text/css"});
        stream.pipe(res);   
    }else if(req.url.match("\.js$")){
        let jsPath = path.join(__dirname, "public/js", req.url);
        let stream = fs.createReadStream(jsPath, "UTF-8");
        res.writeHead(200, {"Content-Type": "text/javascript"});
        stream.pipe(res);   
    }else{
        res.writeHead(404, {"Content-Type": "text/plain"});
        res.end("Page Not found");
    }
});

server.listen(9000);

Project 2

Task 6: Create a simple nodejs server that serves images only (jpeg, jpg, and png).

 ├─ public/
 │  ├─ images/
 │  │  ├─ image.png
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
    let imagePath = path.join(__dirname, "public/images", req.url);
    if(req.url.match("\.jpe?g$")){
        let stream = fs.createReadStream(imagePath);
        res.writeHead(200, {"Content-Type": "image/jpeg"});
        stream.pipe(res);   
    }else if(req.url.match("\.png$")){
        let stream = fs.createReadStream(imagePath);
        res.writeHead(200, {"Content-Type": "image/png"});
        stream.pipe(res);   
    }else{
        res.writeHead(404, {"Content-Type": "text/plain"});
        res.end("Page Not found");
    }
});

server.listen(9000);