- Node Cookbook(Third Edition)
- David Mark Clements Matthias Buus Matteo Collina Peter Elger
- 308字
- 2024-10-29 20:27:02
How to do it...
Let's open meta.js, and begin by loading the modules we'll be using:
const fs = require('fs')
const path = require('path')
const tableaux = require('tableaux')
Next we'll initialize tableaux with some table headers, which in turn will supply a write function which we'll be using shortly:
const write = tableaux(
{name: 'Name', size: 20},
{name: 'Created', size: 30},
{name: 'DeviceId', size: 10},
{name: 'Mode', size: 8},
{name: 'Lnks', size: 4},
{name: 'Size', size: 6}
)
Now let's sketch out a print function:
function print(dir) {
fs.readdirSync(dir)
.map((file) => ({file, dir}))
.map(toMeta)
.forEach(output)
write.newline()
}
The print function won't work yet, not until we define the toMeta and output functions.
The toMeta function is going to take an object with a file property, stat the file in order to obtain information about it, and then return that data, like so:
function toMeta({file, dir}) {
const stats = fs.statSync(path.join(dir, file))
var {birthtime, ino, mode, nlink, size} = stats
birthtime = birthtime.toUTCString()
mode = mode.toString(8)
size += 'B'
return {
file,
dir,
info: [birthtime, ino, mode, nlink, size],
isDir: stats.isDirectory()
}
}
The output function is going to output the information supplied by toMeta, and in cases where a given entity is a directory, it will query and output a summary of the directory contents. Our output functions look like the following:
function output({file, dir, info, isDir}) {
write(file, ...info)
if (!isDir) { return }
const p = path.join(dir, file)
write.arrow()
fs.readdirSync(p).forEach((f) => {
const stats = fs.statSync(path.join(p, f))
const style = stats.isDirectory() ? 'bold' : 'dim'
write[style](f)
})
write.newline()
}
Finally, we can call the print function:
print(process.argv[2] || '.')
Now let's run our program. Assuming our current working directory is the fetching-meta-data folder, we should be able to successfully run the following:
$ node meta.js my-folder
Our program output should look similar to the following screenshot:
