READFILE的NodeJS()来检索文件名 [英] NodeJS readFile() retrieve filename

查看:239
本文介绍了READFILE的NodeJS()来检索文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遍历它包含文件名的数组。对于每个人,我调用 ReadFile的()。当调用相应的回调,我想找回传递给文件名的ReadFile()作为参数。能不能做到?

包围的剪断code,以更好地解释我的意图。

 变种FS =要求(FS);
var中的文件= [first.txt,second.txt];
为(在文件VAR指数){
    fs.readFile(文件[指数],功能(ERR,数据){
        //变种文件名=文件[指数]
        //如果我没有记错的话,ReadFile的()是异步的。因此,当其
        //调用回调函数,文件[指数]可对应于不同的文件。
        //(该指数有进展)。
    });}


解决方案

您也可以使用的forEach 代替循环:

  files.forEach(功能(文​​件){
  fs.readFile(文件,函数(ERR,数据){
    的console.log(读%S ...,文件)
  })
})

I am iterating over an array which contains filenames. For each of them, I invoke readFile(). When the corresponding callback is invoked, I wish to retrieve the filename passed to readFile() as a parameter. Can it be done?

Enclosed a snipped code to better explain my intention.

var fs = require("fs");
var files = ["first.txt", "second.txt"];
for (var index in files) {
    fs.readFile(files[index], function(err, data) {
        //var filename = files[index];
        // If I am not mistaken, readFile() is asynchronous. Hence, when its
        // callback is invoked, files[index] may correspond to a different file.
        // (the index had a progression).
    });

}

解决方案

You could also use forEach instead of a for loop:

files.forEach(function (file){
  fs.readFile(file, function (err, data){
    console.log("Reading %s...", file)
  })
})

这篇关于READFILE的NodeJS()来检索文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆