编写异步代码

弗雷德里克 84

我试图检查我服务器上的文件系统以检查文件是否存在。这个简单的问题实际上变成了一项颇具挑战性的任务。这是我不起作用的基本代码:

  var fs = require('fs');
  var arrayLength = arr.length;
  for (var i = 0; i < arrayLength; i++) {
    var imgfile = arr[i].country
    fs.exists('/var/scraper/public/images/flags' + imgfile + ".png", (exists) => {
      console.log(exists ? 'it\'s there' : 'not here!');
    });                    
  }   

我注意到这不是异步的并且不会起作用。我找到了这个链接:https : //nodejs.org/dist/latest-v9.x/docs/api/fs.html#fs_fs_exists_path_callback

我的代码应该像这样构建。

fs.open('myfile', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EEXIST') {
      console.error('myfile already exists');
      return;
    }

    throw err;
  }

  writeMyData(fd);
 });

我希望得到一些帮助来帮助我重写我的代码以使其异步?

对此有任何帮助将不胜感激。

特里·伦诺克斯

您可以毫无问题地同步执行此操作,这可能需要花费一些时间。如果 fs.exists 函数没有找到文件,我只会确保您的路径完全正确。我在 /flags 之后添加了一个额外的“/”,因为我假设国家名称数组不包括这个。

const fs = require('fs');
const path = require('path');
const imageDir = '/var/scraper/public/images/flags/';

var filesExist = arr.map((imgObj) => {
  const imgfile = imgObj.country;
  let filePath = path.join(imageDir, imgfile + ".png");
  console.log('Checking existance of file: ', filePath);
  // Return an object with 'exists' property and also the file path
  // To just return the path:
  // return fs.existsSync(filePath) ? filePath: path.join(imageDir, "noimg.png")};
  return { exists: fs.existsSync(filePath), path: fs.existsSync(filePath) ? filePath: path.join(imageDir, "noimg.png")};
});

console.log('Files exist: ', filesExist);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章