node 回调函数

来源:互联网 发布:消防工程师教材淘宝 编辑:程序博客网 时间:2024/06/03 20:56

Node.js 回调函数

Node.js 异步编程的直接体现就是回调。

nodeJs编辑器中运行代码:  
错误代码:
 var fs = require('fs');
 fs.readFile('input.txt',function(err,data){console.log(err),data.toString()})

输出: 
undefined
> { [Error: ENOENT:no such file or directory, open 'C:\Program Files (x86)\nodejs\input.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'C:\\Program Files (x86)\\nodejs\\input.txt' }
TypeError: Cannot read property 'toString' of undefined
    at ReadFileContext.callback (repl:1:65)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:303:13)

错误原因: C:\\Program Files (x86)\\nodejs\\input.txt  这里没有 input.txt 文件
解决方案:  C:\\Program Files (x86)\\nodejs   下新建 input.txt 文件
成功代码:
 var fs = require('fs');
  fs.readFile('input.txt',function(err,data){if(err) return console.log(err);console.log(data.toString())})
undefined
> hello!!!



http://notknow.lofter.com/post/19c190_7c4da9

0 0
原创粉丝点击