uglified代码不会写入文件

时间:2012-06-13 11:12:17

标签: javascript node.js uglifyjs

我想遍历目录并获取.js文件并使用uglifyjs和node.js进行uglifying,但我的代码有些问题。下面是我的代码:

var mkdirp = require( 'mkdirp' ),
    walk = require( 'walk' ),
    fs = require( 'fs' ),
    jsp = require( 'uglify-js' ).parser,
    pro = require( 'uglify-js' ).uglify,
    files   = [],
    htmlfilestouglify = [];
// Walker options
var walker  = walk.walk( 'shreedhar/www' , { followLinks: false } );

walker.on('file', function( root, stat, next ) {
    // Add this file to the list of files
    files.push(root + '/' + stat.name);
    next();
});

walker.on( 'end', function() {
    for( var i=0; i<files.length; i++){
        // console.log(files[i]);
        var ext = files[i].split( '.' ).pop();
        if( ext == 'js' ){ 
            console.log( files[i] );
            var orig_code = fs.readFileSync( files[i] ).toString(); //read the content of the file

            // create directory
            var fnarr = files[i].split('/'),
                fname = fnarr.pop( files[i].length-1 ),

                dirlen = fnarr.length,
                dirname = fnarr.slice( 0, dirlen ).join('/');

            mkdirp('build/'+dirname );

            // create file
            fs.open('build/'+dirname+'/'+fname, 'w');

            // uglify the content of the file
            var ast = jsp.parse(orig_code); // parse code and get the initial AST
            ast = pro.ast_mangle(ast); // get a new AST with mangled names
            ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
            var final_code = pro.gen_code(ast); 


            // write uglified code into file

            fs.writeFileSync('build/'+dirname+'/'+fname, final_code); 

        }
        else if( ext == 'html'){
            htmlfilestouglify.push(files[i]);
        }
    }
});

问题是:如果我评论writeFileSync并运行上面的代码,它将创建目录,并在取消注释writeFileSync并运行之后,它会将缩小的代码写入文件,我无法弄清楚我的代码的问题..任何人都可以帮助我。

1 个答案:

答案 0 :(得分:3)

因为mkdirp是异步的。调用同步版本它应该工作:

mkdirp.sync('build/' + dirname);