首页 > 解决方案 > 在 TypeScript 和 Node.js 中定义和排序数组内容数组

问题描述

几周前刚接触 TypeScript,对 JavaScript 了解不多。

我正在尝试遍历指定目录中的所有文件,并将每个文件名(string)和更改时间(number)放入数组数组中,并按更改时间排序。

它看起来像这样:[['natalie.jpg', 143], ['mike.jpg', 20], ['john.jpg', 176], ['Jackie.jpg', 6]]

问题1:不知道如何指定内部数组内容、字符串和数字。类型?界面?班级?元组?

问题2:不知道怎么按变化时间升序排序,使数组变为:[['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)

标签: node.jsarraystypescriptsorting

解决方案


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 )

修改后的时间返回一个Date对象。如果要从新到旧排序,只需反转sort函数中的操作即可。


推荐阅读