Shreedhar
Shreedhar

Reputation: 5640

uglified code will not write into file

i want to traverse the directory and get the .js files and uglifying using uglifyjs and node.js but i have some problems with my code. below is my code :

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]);
        }
    }
});

problem is : if i comment the writeFileSync and run the above code it will create the directory and once again after un commenting the writeFileSync and run, it will write the minified code into files, i couldnt figure out the problem with my code.. can anyone please help me out.

Upvotes: 0

Views: 473

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67128

Because mkdirp is asynchronous. Call the synchronous version and it should work:

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

Upvotes: 3

Related Questions