编写异步代码

时间:2018-03-24 08:22:17

标签: node.js

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

{
  _id: 1,
  title: "123 Department Report",
  tags: [ "G", "STLW" ],
  year: 2014,
  subsections: [
    {
      subtitle: "Section 2.a: Analysis",
      content: "Section 2: This is the content of section 2."
    },
    {
      subtitle: "Section 2.b: Advanced Analysis",
      content: "Section 2: This is the content of section 2."
    } 
  ]
}

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

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

  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!');
    });                    
  }   

我希望能帮助我重写代码以使其异步?

任何对此的帮助都将非常感激。

3 个答案:

答案 0 :(得分:1)

您可以同步执行此操作,没有任何问题,它可能只是需要awile。如果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);

答案 1 :(得分:1)

解决此问题的最简单且耗时的解决方案是简单地使用fs.existsSync您可以找到该方法here的文档。事实上,如果您查看文档中的fs.exists,您会注意到fs.exists至少自上次发布v8 LTS以来已被弃用(这可能就是您遇到问题的原因)

如果您使用支持它的最新版本的节点,这是一个利用async / await的好机会。它可能看起来像这样:

const fs = require('fs');
const { promisify } = require('util');
const existsAsync = promisify(fs.exists);

async function checkFiles (arr) {
  const arrayLength = arr.length;

  for (let i = 0; I < arrayLength; I++) {
    const countryName = arr[i].country;

    const filePath = `/var/scraper/public/images/flags${countryName}.png`; 
    const fileExists = await fs.existsAsync(filePath);

    console.log(`File flags${contryName}.png exists: ${fileExists}`);
  }
}

答案 2 :(得分:1)

这个article可能有助于将你的脑袋缠绕在js上并且它是异步行为。

你的第二段代码看起来不错,但如果你调用的代码在子文件夹中,路径将始终证明是一个问题。这里有一个article来帮助你处理路径。