javascript回调-处理读取文件与fs.readFile
javascript callbacks - handle reading a file with fs.readFile
对于一个项目,我正在使用net模块创建一个'迷你web框架'
我在处理这个回调时遇到了很多麻烦
var sendFile(path) {
fs.readFile(path, config, this.handleRead.bind(this));
}
readFile定义为:
var handleRead = function(contentType, data, err) {
if (err) {
console.log(err); //returns properly
} else {
console.log(data); //returns properly
console.log(contentType) //returning undefined
}
到目前为止,这段代码的工作原理是,我可以捕获错误,也可以正确地编写数据。
我的问题是:我如何通过回调发送contentType ?
I've try -
var sendFile(path) {
var contentType = ContentType['the path type']
fs.readFile(path, config, this.handleRead(contentType).bind(this));
}
但是这会导致data和err未定义。
我对js很陌生,我仍然对如何使用回调感到困惑。任何输入是感激的!
.bind()
让您做的不仅仅是设置"上下文"(函数的this
值)。你也可以在函数中"绑定"参数。
试题:
function sendFile(path) {
var contentType = ContentType['the path type']
fs.readFile(path, config, this.handleRead.bind(this, contentType));
}
这将传递一个回调,其上下文设置为this
,其第一个参数设置为contentType
。只要这个回调是用data
(也可能是err
)调用的,那么一切都会正常工作。
相关文章:
- 为什么fs.readFile在windows上花费太多时间
- 为什么这个 fs.readFile 循环没有将其结果推送到我的数组
- Node res.write() and fs.readFile
- 使用Node.js'fs.readFile()返回字符串出现的行
- 节点.js解析 fs.readFile() 的意外数字转换
- fs.readFile 的替代方法,用于在 Express 中使用 res.json 时加载车把模板
- 使用 require vs fs.readFile 读取 json 文件内容
- Angular 没有从 FS.readFile 获取带有承诺的数据
- Async.series 不适用于 fs.readFile
- Javascript / NodeJs - fs.readFile 在读取文件之前使用回调
- 从 fs.readFile 获取数据
- Hapijs、fs.readfile、fs.writefile和childprocess.exec我如何控制异步
- 存储nodejs fs.readfile's产生一个变量并传递给全局变量
- 为什么fs.readFile返回缓冲区
- 为什么我不能使用响应?写入fs.readFile
- javascript回调-处理读取文件与fs.readFile
- 在fs.readfile在使用fs.readfile.bind(context,pathArgument)时被调用
- fs.readFile返回Buffer对象,toString将使终端报错
- React和Electron with Bablify: Uncaught TypeError: fs.readFile
- TypeError: fs.readFile不是一个函数