Node.js创建目录实例

webgame项目经常要维护更新,先在创建一个批次号,然后上传至更新服务器上然后再分别copy文件至各服务器的一个临时目录,然后更新结束后删除该临时目录。而本地需要根据批次号创建一系统的文件夹目录。之前是先手动创建一个批次号文件夹,然后写一个bat,创建更新批次相应的文件夹。现在如果用node.js写的话,比较简单。系统盘当前登录用户目录放一个update.js文件---好处是直接cmd的时候就是该目录了,节省时间。

 

调用的话就比较简单了。命令行里输入:“node update.js zh(语言包,不同的语言zh/tw/vi分别在不同的目录中)  批次号”

 

本来是想尝试在桌面文件夹创建一个bat文件,创建完目录后双击该bat文件就可以打开新创建的更新目录,但发现将utf-8转成ascii时出了问题,懒得去折腾了,先将就着用用了。update.js的代码也比较简单:

   1: var fs = require('fs');
   2: var buffer = require('buffer');
   3:  
   4: var update_dir = {
   5:     'zh' : 'E:/xx/【国内】/',
   6:     'tw' : 'E:/xxx/【台湾】/'
   7: };
   8:  
   9: ~(function() {
  10:     //获取命令行参数
  11:     var args = process.argv.splice(2);
  12:     
  13:     if (args.length < 2) {
  14:         console.log("传入的参数有误");
  15:         return ;
  16:     }
  17:     
  18:     var language = args[0];
  19:     var dirPath = update_dir[language];
  20:     
  21:     if (!dirPath) {
  22:         console.log('请传入正确的语言包 zh/tw');
  23:         return ;
  24:     }
  25:  
  26:     var updateNo = args[1];
  27:     
  28:     console.log('\n更新批次号为:' + updateNo + '\n');
  29:  
  30:     var goalDirPath = dirPath + updateNo;
  31:  
  32:     if (fs.existsSync(goalDirPath)) {
  33:         console.log('已经创建过此更新目录了');
  34:     } else {
  35:         fs.mkdirSync(goalDirPath);
  36:  
  37:         console.log('更新目录已创建成功\n');
  38:     }
  39:  
  40:     //创建Common、HttpRoot、dynConfig
  41:     var commonDirPath = goalDirPath + '/Common';
  42:  
  43:     if (!fs.existsSync(commonDirPath)) {
  44:         fs.mkdirSync(commonDirPath);
  45:  
  46:         console.log('Common目录创建成功');
  47:     }
  48:  
  49:     var arr = ['HttpRoot', 'dynConfig'];
  50:  
  51:     for (var i = 0, len = arr.length; i < len; i++) {
  52:         var a = arr[i];
  53:         var b = commonDirPath + '/' + a;
  54:  
  55:         if (!fs.existsSync(b)) {
  56:             fs.mkdirSync(b);
  57:  
  58:             console.log(a + '目录创建成功');
  59:         }
  60:     }
  61:     
  62:     /* 很遗憾这里未能实现想要的效果,如果路径没有中文倒是没什么问题...
  63:     //在桌面创建直接打开目录的bat
  64:     var desktopDirPath = 'G:/Documents and Settings/xxx/桌面/';
  65:     var quickBatPath = desktopDirPath + 'o_dir.bat';
  66: 
  67:     if (fs.existsSync(quickBatPath)) {
  68:         fs.unlinkSync(quickBatPath);
  69:         console.log('\n删除“' + quickBatPath + '”文件');
  70:     }
  71: 
  72:     var batFileContentStr = 'explorer.exe "' + commonDirPath.replace(/\//g, '\\') + '\\HttpRoot"';
  73:     
  74:     var buffer = new Buffer(batFileContentStr, "utf8");
  75:     
  76:     fs.writeFileSync(quickBatPath, buffer, 'utf8');
  77:     */
  78: })();
  79:  
  80:  

 

参考:http://nodemanual.org/0.8.5/nodejs_ref_guide/fs.html

posted @ 2012-08-06 21:20  meteoric_cry  阅读(21886)  评论(0编辑  收藏  举报