Skip to content
This repository has been archived by the owner on Aug 31, 2024. It is now read-only.

File streaming exercise. #4

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
File streaming excercise.
  • Loading branch information
hemanth committed Jul 25, 2014
commit 70f6b11b3e96fd2f27f1395ea1e253da1e26b706
17 changes: 9 additions & 8 deletions exercises/menu.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
[
"HELLO_KOA",
"ROUTING",
"REQUEST_BODY",
"RESPONSE_BODY",
"MIDDLEWARE",
"ERROR_HANDLING",
"COOKIE",
"TEMPLATING"
"HELLO_KOA",
"ROUTING",
"REQUEST_BODY",
"RESPONSE_BODY",
"MIDDLEWARE",
"ERROR_HANDLING",
"COOKIE",
"TEMPLATING",
"STREAM_FILE"
]
6 changes: 6 additions & 0 deletions exercises/stream_file/exercise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

var exercise = require('../../exercise');

module.exports = exercise.push('/hello', function (data, res, stream) {
stream.write(data.toString() + '\n');
}).generate();
19 changes: 19 additions & 0 deletions exercises/stream_file/problem.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Create a koa server that listens on a port passed from the command line and replies with contents of the requested file when an HTTP GET request is sent to `/<file_name>`

P.S: The fun part is, it shall be using a Stream here ;)

HINTS:

* Create a file named `hello` in the same dir where the `program.js` is present and contents of it being `Hello from Koa!`

* When request for `/hello` the server must responsed with the contents of the file `hello`

* When request for something else either than `/hello` it must responsed saying `File not Found.` ( As expected. )

* The path to the file will be `path = __dirname + this.path;`

* You can use `fs` module to check if the file is present or not and set the body to `fs.createReadStream(path)`.

So, what are you waiting for?

Go ahead and code, good luck!
1 change: 1 addition & 0 deletions exercises/stream_file/solution/hello
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello from Koa!
20 changes: 20 additions & 0 deletions exercises/stream_file/solution/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var koa = require('koa');
var fs = require('fs');
var app = module.exports = koa();
var path = require('path');
var extname = path.extname;

// try GET /app.js

app.use(function * () {
var path = __dirname + this.path;
if (fs.lstatSync(path).isFile()) {
this.type = extname(path);
this.body = fs.createReadStream(path);
} else {
this.satus = 404;
this.body = "File not found.";
}
});

app.listen(process.argv[2]);