var fs = require('fs') // fs 文件系统
var stdin = process.stdin
var stdout = process.stdout
var stats = [] fs.readdir(process.cwd(), function(err, files) {
console.log('')
if (!files.length) {
return console.log(' \003[31m No files to show!\003[39\n')
}
console.log(' Select which file or directory you want to see\n') function file(i) {
var filename = files[i]
fs.stat(__dirname + '/' + filename, function(err, stat) { // fs.stat会给出文件或目录的元数据
stats[i] = stat
if (stat.isDirectory()) {
console.log(' '+i+' \033[36m' + filename + '/\033[39m')
} else {
console.log(' '+i+' \033[90m' + filename + '/\033[39m')
}
if (++i == files.length) {
read()
} else {
file(i)
}
})
}
function read() {
console.log('')
stdout.write(' \033[33mEnter you choice: \033[39m')
stdin.resume()
stdin.setEncoding('utf-8')
stdin.on('data', option)
} function option(data) {
var filename = files[Number(data)]
if (!filename) {
stdout.write(' \033[31mEnter your choice: \033[39m')
} else {
stdin.pause()
if (stats[Number(data)].isDirectory()) {
fs.readdir(__dirname + '/' + filename, function(err, files) {
console.log('')
console.log(' (' + files.length + ' files)')
files.forEach(function(file) {
console.log(' - ' + file)
})
console.log('')
})
} else {
fs.readFile(__dirname + '/' + filename, 'utf-8', function(err, data) {
console.log('')
console.log('\033[90m' + data.replace(/(.*)/g, ' $1') + '\033[39m')
})
}
}
} file(0)
})
console.log('Hello world')
process.stdout.write('Hello world')
console.log('Hello world')
console.log内部做了这样的事情:它在指定的字符串后加上\n(换行)字符,并将其写到stdout流中