Welcome to the Linux Foundation Forum!

Lab 13.2 Watching

Lab 13.2 Watching is actually located in the ch-13 labs-1 folder and the 13.1 - Read Directory and Write File is located in the labs-2 folder but whatever, I can overlook that. I need help solving the 13.2 Watching lab. The lab instructions state, "The goal is to ensure that the ​answer​ variable is set to the newly created file." and my actual results are the newly created file every time as confirmed in the assert actual and when I log the file creation. The assert always logs the previously created file as expected though. I must be missing something and would appreciate some direction.

Comments

  • @olmryoung

    thanks for the heads up on the ordering, it's being corrected now.

    Can you post some code as a starting point for a discussion about this?

  • So I put my solution below, my tests passed, I made some comments to describe the program.

    First the program creates a file named project,
    Then it adds a file that is a 'pre-existing file' to project,
    Later the program uses the fs.watch() function to watch the directory we created, project. After the process begins watching the directory the next part of the program involves creating a new file, a new directory, and changing the permissions.

    Each time the one of these events occurs the callback function is called.

    Within the callback function we must create some logic so that we only assign the variable answer to a newly created file in the project directory.

    I achieved this by using the stats object. Importantly we must avoid the newly created directory, to select for files we can use the fs.stats.isFile() method. The other piece of logic is birth time === change time.

    The code passes.

    The comments were not rendering correctly so I used various commenting characters to coerce the markdown to render correctly.

    The OUTPUT is at the bottom. 😀

    'use strict'
    const assert = require('assert')
    const { join } = require('path')
    const fs = require('fs')
    const { promisify } = require('util')
    const timeout = promisify(setTimeout)
    const project = join(__dirname, 'project')
    try { fs.rmdirSync(project, {recursive: true}) } catch (err) {
      console.error(err)
    }
    /* project directory is made */
    fs.mkdirSync(project)
    
    let answer = ''
    
    async function writer () {
      const { open, chmod, mkdir } = fs.promises
      const pre = join(project, Math.random().toString(36).slice(2))
      /* pre-existing file is created */
      const handle = await open(pre, 'w')
      await handle.close()
      await timeout(500)
      exercise(project)
      const file = join(project, Math.random().toString(36).slice(2))
      const dir = join(project, Math.random().toString(36).slice(2))
      /* another file is made */
      const add = await open(file, 'w')
      await add.close()
      /* a directory is created */
      await mkdir(dir)
      /* Permissions are changed */
      await chmod(pre, 0o644)
      await timeout(500)
      assert.strictEqual(
        answer, 
        file, 
        'answer should be the file (not folder) which was added'
      )
      console.log('passed!')
      process.exit()
    }
    
    writer().catch((err) => {
      console.error(err)
      process.exit(1)
    })
    
    
    function exercise (project) {
      const files = new Set(fs.readdirSync(project))
      fs.watch(project, (evt, filename) => {
        try { 
          const filepath = join(project, filename)
          const stat = fs.statSync(filepath)
          /* TODO - only set the answer variable if the filepath
          // is both newly created AND does not point to a directory
    
    
          //============================ */
    
          const { birthtimeMs, ctimeMs } = stat;
          /*isFile() filters out dir events
          // birthtimeMs and ctimeMs selects for file creation events. */
          if (stat.isFile() && birthtimeMs === ctimeMs) {
            answer = filepath
            console.log(answer)
          }
        /*  //============================= */
        } catch (err) {
    
        } 
      })
    }
    

    OUTPUT

    /home/ec2-user/environment/project/hkzktf59p0l
    passed!
    
    
  • hey @andrewpartrickmiller - great work! would you mind putting solutions inside <details> elements, e.g:

    <details>
    <summary> SPOILERS </summary>
    {YOUR CODE HERE}
    </details>
    
  • fanfly
    fanfly Posts: 1

    I used if (fs.statSync(project).isDirectory() && birthtimeMs === ctimeMs) instead of isFile()
    Someone can tell why we should use this method about fs.statSync(filepath) and not use isDirectory()?

  • axel.latour
    axel.latour Posts: 2
    edited April 2021

    Hello @davidmarkclements !

    Doing this exercise, I'm facing a problem. It seems that the chmod applied on the pre file doesn't trigger any event.

    Just changing this in the exercise method

          if(stat.isFile()) {
            answer = filepath
          }
    

    And it passed, while I was waiting for it to fail because the last file which should trigger an event is the pre one.

    I'm working on Windows 10. Do you have any idea ?

    Thanks !

  • @fanly fs.statSync(project).isDirectory() === false would be a more accurate implementation than isFile() because isFile is for regular files (e.g. not sockets etc) where is !isDirectory() would be for any non-directory. So you are more correct.

  • @axel.latour - can you try this on on latest v12 or v14, it may be a windows related bug

  • @davidmarkclements Thanks for your answer, I did it using v12, just tried with v14, and still the same issue

  • ok thanks @axel.latour I'm going to need to check this out on Windows 10

  • jorams
    jorams Posts: 1

    Hello @axel.latour !

    Apparently fsPromises.chmod(path, mode) on Windows only has an effect for modes 0o111, 0o444, 0o555 which make the file read-only.

    For example: await chmod(pre, 0o444) is effective and triggers the 'change' event.

  • great observation @jorams, content is being updated on your suggestion

This discussion has been closed.

Categories

Upcoming Training