title: Google Cloud Function - Error: ENOENT: no such file or directory
body: <p>I'm trying to do a simple function that resizes a newly uploaded image in Storage. I use the following to help me do that: </p>
  
  <pre><code>import { tmpdir } from 'os';
  import { join, dirname } from 'path';
  import * as sharp from 'sharp';
  import * as fs from 'fs-extra';
  </code></pre>
  
  <p>When this code executes: </p>
  
  <pre><code>await bucket.file(filePath).download({
      destination: tmpFilePath
  });
  </code></pre>
  
  <p>I get the following <strong><em>error</em></strong> in the Google Cloud Function logs: </p>
  
  <blockquote>
    <p>Error: ENOENT: no such file or directory, open '/tmp/images/1542144115815_Emperor_penguins.jpg' at Error (native)</p>
  </blockquote>
  
  <p>Here is the full code [segment]: </p>
  
  <pre><code>const gcs = admin.storage();
  const db = admin.firestore();
  
  import { tmpdir } from 'os';
  import { join, dirname } from 'path';
  
  import * as sharp from 'sharp';
  import * as fs from 'fs-extra';
  
  export const imageResize = functions.storage
      .object()
      .onFinalize(async object =&gt; {
          console.log('&gt; &gt; &gt; &gt; &gt; &gt; &gt; 1.3 &lt; &lt; &lt; &lt; &lt; &lt; &lt;');
          const bucket = gcs.bucket(object.bucket);
          console.log(object.name);
          const filePath = object.name;
          const fileName = filePath.split('/').pop();
          const tmpFilePath = join(tmpdir(), object.name);
  
          const thumbFileName = 'thumb_' + fileName;
          const tmpThumbPath = join(tmpdir(), thumbFileName);
  
          console.log('step 1');
          // Resizing image
          if (fileName.includes('thumb_')) {
              console.log('exiting function');
              return false;
          }
          console.log('step 2');
          console.log(`filePath: ${filePath}`);
          console.log(`tmpFilePath: ${tmpFilePath}`);
          await bucket.file(filePath).download({
              destination: tmpFilePath
          });
          console.log('step 3');
          await sharp(tmpFilePath)
              .resize(200, 200)
              .toFile(tmpThumbPath);
  
          await bucket.upload(tmpThumbPath, {
              destination: join(dirname(filePath), thumbFileName)
          });
  </code></pre>
  
  <p><strong>UPDATE 1</strong>: added <code>await fs.ensureDir(tmpFilePath);</code> to ensure the filepath exists. Now getting a new error: </p>
  
  <blockquote>
    <p>Error: EINVAL: invalid argument, open '/tmp/images/1542146603970_mouse.png' at Error (native)</p>
  </blockquote>
  
  <p><strong>UPDATE 2 SOLVED</strong>: Added a <em>solution</em> as an <em>Answer</em> below. </p>