Julia O
Julia O

Reputation: 241

Define and sort array of array content in TypeScript and Node.js

Just took up TypeScript a couple of weeks ago without much knowledge in JavaScript.

I am trying to go through all the files in the specified directory and put each file name (string) and change time (number) into an array of array and sort by change time.

It looks like this: [['natalie.jpg', 143], ['mike.jpg', 20], ['john.jpg', 176], ['Jackie.jpg', 6]]

Problem 1: I do not know how to specify the inner array content, string and number. Type? Interface? Class? Tuple?

Problem 2: I do not know how to sort by change time in ascending order, so that the array changes to: [['Jackie.jpg', 6], ['mike.jpg', 20], ['natalie.jpg', 143], ['john.jpg', 176]]

import fs from 'fs'

const dirPath = '/home/me/Desktop/'

type imageFileDesc = [string, number] // tuple

const imageFileArray = [imageFileDesc] // ERROR HERE!

function readImageFiles (dirPath: string) {
  try {
    const dirObjectNames = fs.readdirSync(dirPath)

    for (const dirObjectName of dirObjectNames) {
      const dirObject = fs.lstatSync(dirPath + '/' + dirObjectName)
      if (dirObject.isFile()) {
        imageFileArray.push([dirObjectName, dirObject.ctimeMs]) // ERROR HERE!
      }
    }

    imageFileArray.sort(function (a: number, b: number) {
      return b[1] - a[1] // ERROR HERE! Can we do something like b.ctime - a.ctime?
    })
  } catch (error) {
    console.error('Error in reading ' + dirPath)
  }
}

readImageFiles(dirPath)
console.log(imageFileArray)

Upvotes: 0

Views: 216

Answers (1)

bitomic
bitomic

Reputation: 170

import * as fs from 'fs'

// Read files in folder
const files = fs.readdirSync( './files' )
// This will store the file name and their modification time
const imageFileArray: [ string, Date ][] = []

for ( const file of files ) {
    // You can get a file's last modified time through fs.stat
    const stats = fs.statSync( `./files/${file}` )
    const modifiedTime = stats.mtime
    // Push a tuple containing the filename and the last modified time
    imageFileArray.push( [ file, modifiedTime ] )
}

// Sort from older to newer
const sorted = imageFileArray.sort( (a, b) => a[1].getTime() - b[1].getTime() )

console.log( sorted )

The modified time returns a Date object. If you want to sort from newer to older, just invert the operation in the sort function.

Upvotes: 1

Related Questions