node.js - 在 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)
解决方案
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
函数中的操作即可。
推荐阅读
- sql - 我将如何计算空值但仍指定在历史/贷款表中计数
- java - 为什么多个@ComponentScan 注释会破坏我的 AspectJ 事务?
- ios - Xcode 模拟器中的 ARC 是否存在已知问题?
- ios - 在 iOS swift3 中并行处理视频录制和电话功能
- android - 如何在 SlideUpPanelLayout 上回收视图滚动?
- javascript - Javascript CORS 请求,不存在带有 200 状态代码的“Access-Control-Allow-Origin”标头
- algorithm - 在不使用谷歌地图的情况下检查多边形内的 LatLng
- android - Google Play:应用程序只能从平板电脑下载
- javascript - map 函数迭代取一个道具值动态
- sql - 如何在 SQL Server 中对 1:15 这种类型的值求和