1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #!/usr/bin/env node
console.log('文件创建时间读取并写入文件指定字段demo'); var fs = require("fs"); var file = "./txt";
fs.readdir("./",function(err,files){ var len=files.length; var file=null; for(var i=0;i<len;i++){ file=files[i]; console.log("读取文件:",file); if(file.indexOf(".md")>-1){ console.log("处理文件:",file); writeFileTime(file,fs); } } });
function writeFileTime(file,fs){ fs.readFile(file, 'utf8',function(err, data) { if (err) return console.log("读取文件内容错误:",err); console.log("文件"+file+"的内容:",data); fs.stat(file,function(err, stats) { if (err) return console.log("读取文件信息错误:",err); console.log("文件"+file+"的信息:",stats); console.log("创建时间是:",stats.mtime); console.log("格式化",getFormatDate(stats.mtime)); var result = data.replace(/categories:/g, "updated: "+getFormatDate(stats.mtime)+"\r"+"categories:"); console.log("修改后文件内容为:",result); fs.writeFile(file, result, 'utf8',function(err) { if (err) return console.log("写文件错误:",err); }); }); }); }
function getFormatDate(timeStr, dateSeparator, timeSeparator) { dateSeparator = dateSeparator ? dateSeparator : "-"; timeSeparator = timeSeparator ? timeSeparator : ":"; var date = new Date(timeStr), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), hour = date.getHours(), minute = date.getMinutes(), seconds = date.getSeconds(), Y = year + dateSeparator, M = ((month + 1) > 9 ? (month + 1) : ('0' + (month + 1))) + dateSeparator, D = (day > 9 ? day : ('0' + day)) + ' ', h = (hour > 9 ? hour : ('0' + hour)) + timeSeparator, m = (minute > 9 ? minute : ('0' + minute)) + timeSeparator, s = (seconds > 9 ? seconds : ('0' + seconds)), formatDate = Y + M + D + h + m + s; return formatDate; }
|