我想遍历目录并获取 .js 文件并使用 uglifyjs 和 node.js 进行丑化,但我的代码存在一些问题。下面是我的代码:
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 并运行后再次将缩小的代码写入文件,我无法找出我的代码的问题.. 可以任何人请帮帮我。