Learning Node.js

HELLO WORLD (Exercise 1 of 13)

Write a program that prints the text "HELLO WORLD" to the console
(stdout).

console.log("HELLO WORLD")

BABY STEPS (Exercise 2 of 13)

Write a program that accepts one or more numbers as command-line arguments
and prints the sum of those numbers to the console (stdout).

let sum = 0

process.argv.forEach((item,index) => {
    if(index>1)
        sum+=Number(item)
});
console.log(sum)

MY FIRST I/O! (Exercise 3 of 13)

Write a program that uses a single synchronous filesystem operation to
read a file and print the number of newlines (\n) it contains to the
console (stdout), similar to running cat file | wc -l.

The full path to the file to read will be provided as the first
command-line argument (i.e., process.argv[2]). You do not need to make
your own test file.

let fs = require("fs")

let data = fs.readFileSync(process.argv[2],"utf-8");
console.log(data.split("\n").length -1);

MY FIRST ASYNC I/O! (Exercise 4 of 13)

Write a program that uses a single asynchronous filesystem operation to
read a file and print the number of newlines it contains to the console
(stdout), similar to running cat file | wc -l.

The full path to the file to read will be provided as the first
command-line argument.

var fs = require("fs")

fs.readFile(process.argv[2],"utf-8",(err,data) => {
    let newlines = 0
    if(err) console.error(err)
    for (let codepoint of data){

        if(codepoint==="\n")
            newlines++;
    }
    console.log(newlines)
});

FILTERED LS (Exercise 5 of 13)

Create a program that prints a list of files in a given directory,
filtered by the extension of the files. You will be provided a directory
name as the first argument to your program (e.g. '/path/to/dir/') and a
file extension to filter by as the second argument.

For example, if you get 'txt' as the second argument then you will need to
filter the list to only files that end with .txt. Note that the second
argument will not come prefixed with a '.'.

Keep in mind that the first arguments of your program are not the first
values of the process.argv array, as the first two values are reserved for
system info by Node.

The list of files should be printed to the console, one file per line. You
must use asynchronous I/O.

let fs = require("fs")

fs.readdir(process.argv[2], (err, list) => {
    if (err) return console.error(err)
    list.forEach((item) => {
        if (item.endsWith("." + process.argv[3]))
            console.log(item)
    })

});

MAKE IT MODULAR (Exercise 6 of 13)

This problem is the same as the previous but introduces the concept of
modules. You will need to create two files to solve this.

Create a program that prints a list of files in a given directory,
filtered by the extension of the files. The first argument is the
directory name and the second argument is the extension filter. Print the
list of files (one file per line) to the console. You must use
asynchronous I/O.

You must write a module file to do most of the work. The module must
export a single function that takes three arguments: the directory name,
the filename extension string and a callback function, in that order. The
filename extension argument must be the same as what was passed to your
program. Don't turn it into a RegExp or prefix with "." or do anything
except pass it to your module where you can do what you need to make your
filter work.

The callback function must be called using the idiomatic node(err, data)
convention. This convention stipulates that unless there's an error, the
first argument passed to the callback will be null, and the second will be
your data. In this exercise, the data will be your filtered list of files,
as an Array. If you receive an error, e.g. from your call to
fs.readdir(), the callback must be called with the error, and only the
error, as the first argument.

You must not print directly to the console from your module file, only
from your original program.

In the case of an error bubbling up to your original program file, simply
check for it and print an informative message to the console.

These four things are the contract that your module must follow.

  1. Export a single function that takes exactly the arguments described.
  2. Call the callback exactly once with an error or some data as described.
  3. Don't change anything else, like global variables or stdout.
  4. Handle all the errors that may occur and pass them to the callback.

The benefit of having a contract is that your module can be used by anyone
who expects this contract. So your module could be used by anyone else who
does learnyounode, or the verifier, and just work.

let fs = require("fs")

module.exports =  function foo(dir,ext,callback) {
    fs.readdir(dir, (err, data) => {
        if(err)  return callback(err)
        let list = []
        data.forEach((item) => {
            if (item.endsWith("." + ext))
                list.push(item)
        })
        callback(null,list)
    });
}

let foo = require('./module2.js');

foo(process.argv[2],process.argv[3],(err,data) =>{
    if(err)
        return console.error(err)
    data.forEach((item)=>{
        console.log(item)
    })

});

HTTP CLIENT (Exercise 7 of 13)

Write a program that performs an HTTP GET request to a URL provided to you
as the first command-line argument. Write the String contents of each
"data" event from the response to a new line on the console (stdout).

let http = require('http')

http.get(process.argv[2],(res)=>{
  res.setEncoding('utf-8')
  res.on('error',(error)=>{
      return console.error(error)
  })
  res.on("data",(data)=>{
      console.log(data)
  })
}).on("error",console.error)

HTTP COLLECT (Exercise 8 of 13)

Write a program that performs an HTTP GET request to a URL provided to you
as the first command-line argument. Collect all data from the server (not
just the first "data" event) and then write two lines to the console
(stdout).

The first line you write should just be an integer representing the number
of characters received from the server. The second line should contain the
complete String of characters sent by the server.

let http = require("http")
let concatstream = require("concat-stream")

http.get(process.argv[2], (res) => {

  res.on("error", console.error)
  res.on("data", (data) => {

  })
  res.pipe(concatstream((data) => {
      console.log(data.toString().length)
      console.log(data.toString())
  }))
})

JUGGLING ASYNC (Exercise 9 of 13)

This problem is the same as the previous problem (HTTP COLLECT) in that
you need to use http.get(). However, this time you will be provided with
three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the URLs
and print it to the console (stdout). You don't need to print out the
length, just the data as a String; one line per URL. The catch is that you
must print them out in the same order as the URLs are provided to you as
command-line arguments.

let http = require('http')

const list = []
list.push(process.argv[2])
list.push(process.argv[3])
list.push(process.argv[4])
const data = []


function fetch(url, callback) {
    http.get(url, res => {
        let buff = []
        res.on("data", data => {
            buff += data
        })
        res.on("end", () => {
            data.push(buff.toString())
            callback()
        })
    })
}

fetch(list[0], () => {
    fetch(list[1], () => {
        fetch(list[2], () => {
            data.forEach(item => {
                console.log(item)
            })
        })
    })
})

TIME SERVER (Exercise 10 of 13)

Write a TCP time server!

Your server should listen to TCP connections on the port provided by the
first argument to your program. For each connection you must write the
current date & 24 hour time in the format:

"YYYY-MM-DD hh:mm"

followed by a newline character. Month, day, hour and minute must be
zero-filled to 2 integers. For example:

"2013-07-06 17:42"

After sending the string, close the connection.

let net = require('net')

net.createServer(socket => {
    let date = new Date()
    "x".padStart(3, "0")
    socket.end(date.getFullYear() + "-" + ((date.getMonth() + 1).toString().padStart(2, "0"))
        + "-" + (date.getDate().toString().padStart(2, "0")) + " " + date.getHours() + ":" + date.getMinutes()+"\n")
}).listen(process.argv[2])

HTTP FILE SERVER (Exercise 11 of 13)

Write an HTTP server that serves the same text file for each request it
receives.

Your server should listen on the port provided by the first argument to
your program.

You will be provided with the location of the file to serve as the second
command-line argument. You must use the fs.createReadStream() method to
stream the file contents to the response.

let http = require("http")
let fs = require("fs")
const file = process.argv[3]
console.log(file)
http.createServer((req,res) => {
    fs.createReadStream(file).pipe(res)
}).listen(process.argv[2])

HTTP UPPERCASERER (Exercise 12 of 13)

Write an HTTP server that receives only POST requests and converts
incoming POST body characters to upper-case and returns it to the client.

Your server should listen on the port provided by the first argument to
your program.

let http = require("http")
let map = require("through2-map")

http.createServer((req, res) => {
    if (req.method == "POST") {
        req.pipe(map(chunk => {
            return chunk.toString().toUpperCase()
        })).pipe(res)
    }
}).listen(process.argv[2])

HTTP JSON API SERVER (Exercise 13 of 13)

Write an HTTP server that serves JSON data when it receives a GET request
to the path '/api/parsetime'. Expect the request to contain a query string
with a key 'iso' and an ISO-format time as the value.

For example:

/api/parsetime?iso=2013-08-10T12:10:15.474Z

The JSON response should contain only 'hour', 'minute' and 'second'
properties. For example:

{
  "hour": 14,
  "minute": 23,
  "second": 15
}

Add second endpoint for the path '/api/unixtime' which accepts the same
query string but returns UNIX epoch time in milliseconds (the number of
milliseconds since 1 Jan 1970 00:00:00 UTC) under the property 'unixtime'.
For example:

{ "unixtime": 1376136615474 }

Your server should listen on the port provided by the first argument to
your program.

let http = require("http")
let url = require("url")

http.createServer((req, res) => {
    let urlObj = url.parse(req.url, true)
    let isoDate = urlObj.query.iso
    let date = new Date(isoDate)
    let result
    if (urlObj.pathname == "/api/parsetime") {
        result = res.end(JSON.stringify({
            hour: date.getHours(),
            minute: date.getMinutes(),
            second: date.getSeconds()
        }))
    }

    if (urlObj.pathname == "/api/unixtime") {
        result = res.end(JSON.stringify({
            unixtime: date.getTime(),
        }))
    }
    if (result) {
        res.writeHead(200, {'Content-Type': 'application/json'})
        res.end(result)
    }
    else {
        res.writeHead(404)
        res.end()
    }

}).listen(process.argv[2])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末故源,一起剝皮案震驚了整個濱河市殉簸,隨后出現(xiàn)的幾起案子跋核,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機捡偏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來峡迷,“玉大人银伟,你說我怎么就攤上這事』娓悖” “怎么了彤避?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長看杭。 經(jīng)常有香客問我忠藤,道長,這世上最難降的妖魔是什么楼雹? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任模孩,我火速辦了婚禮尖阔,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘榨咐。我一直安慰自己介却,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布块茁。 她就那樣靜靜地躺著齿坷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪数焊。 梳的紋絲不亂的頭發(fā)上永淌,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天,我揣著相機與錄音佩耳,去河邊找鬼遂蛀。 笑死,一個胖子當(dāng)著我的面吹牛干厚,可吹牛的內(nèi)容都是我干的李滴。 我是一名探鬼主播,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蛮瞄,長吁一口氣:“原來是場噩夢啊……” “哼所坯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起挂捅,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤芹助,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后籍凝,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體周瞎,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡苗缩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年饵蒂,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片酱讶。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡退盯,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出泻肯,到底是詐尸還是另有隱情渊迁,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布灶挟,位于F島的核電站琉朽,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏稚铣。R本人自食惡果不足惜箱叁,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一楼眷、第九天 我趴在偏房一處隱蔽的房頂上張望塔沃。 院中可真熱鬧,春花似錦、人聲如沸勺择。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽漱贱。三九已至,卻和暖如春妓笙,著一層夾襖步出監(jiān)牢的瞬間若河,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工寞宫, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留牡肉,地道東北人。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓淆九,卻偏偏與公主長得像统锤,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子炭庙,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容