地址在这里 https://github.com/workshopper/learnyounode ,全局安装就可以,下载下来的工程里也有答案,不过还是自己做做比较有意思,之前都是很笼统的看,这里会有一些细节的东西,英文也不难理解,记录下

第二个题目,babyStep,了解了下progess的参数,以及运算,还看了下reduce的用法,没怎么用过这个,我用map实现的

console.log(process.argv) ----babySteps.js

test hna$ node babySteps.js 1 2 3  

[ '/usr/local/bin/node',

  '/Users/hna/Desktop/study/learnyounode-master/test/babySteps.js',

  '1',

  '2',

  '3' ]

var total = 0
process.argv.map(function (currentValue, index) {
  if (index > 1) {
    total = total + Number(currentValue)
  }
})
console.log(total)

这里也记录下reduce的用法 

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)--感觉这个比map多个total

 

第三个题目,统计行数,这里不太明白为什么减一操作。。我自己用node试了,不减才是正确的啊。。。

var fs = require('fs');
var buffer = fs.readFileSync(process.argv[2]);
var str = buffer.toString().split('\n').length;
console.log(str-1);

熟悉了下fs,读进去是buffer,打印看了下,经常看到但是不知道。。。

 

第四个题目,练习异步读取

var fs = require('fs');
fs.readFile(process.argv[2],'utf8',function (err,data) {
  if(err) throw err;
  console.log(data.split('\n').length -1)
})

第五个题目,练习目录的读取,及path的用法,大概扫了一遍,path.extname(file) 获取文件后缀

var fs = require('fs')
var path = require('path')

fs.readdir(process.argv[2], function (err, list) {
  if(err) throw err;
  list.filter(function (file) {
    return path.extname(file) === '.' + process.argv[3]
  }).map(function (file) {
    console.log(file)
  })
});

第六个题目,练习module的export

test.js

var test = require('./moduleExport')
test(process.argv[2], process.argv[3], function (error, filelist) {
  if (error) {
    console.log(error)
  }
  else {
    filelist.forEach(function (entry) {
      console.log(entry)
    })
  }

})

moduleExport.js

var fs = require('fs')
var path = require('path')

module.exports = function (dirName, extension, callback) {
  fs.readdir(dirName, function (err, list) {
    if (err) return callback(err)
    var filerList = list.filter(function (file) {
      return path.extname(file) === '.' + extension
    })

    callback(null, filerList)
  })

}

learnyounode verify module/test.js ../node_apidoc md

 

第七个题目,http模板

var http = require('http')

var http = require("http")
http.get(process.argv[2],function (res) {
  res.setEncoding('utf8')
  res.on('data', console.log)
  res.on('error', console.error)
})

运行的命令是  learnyounode verify httpclient.js http://nodejs.org/dist/index.json  看了下官网的介绍

 

 

 

 

 

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐