srod / node-minify Goto Github PK
View Code? Open in Web Editor NEWLight Node.js module that compress javascript, css and html files
Home Page: https://node-minify.2clics.net
License: MIT License
Light Node.js module that compress javascript, css and html files
Home Page: https://node-minify.2clics.net
License: MIT License
The current implementation relies on processing of the uglify script header:
which Windows won't do, even within a cygwin environment. The uglify script can't be launched via the command as it is currently written.
Is there any way we cannot have to set full path to node-minify.js for accessing require('c:/users/name/appdata/roaming/npm/npm_module/node-minify/libs/node-minify');
When i have server compressor js file one different location, i have to set full path to make it work, can i do it like using require('http"), require('express'), and so on require('node-minify')?
Is it possible to run it in command line mode? Tried with npm install node-minify -g
for global module but it doesn’t work…
It seems the _fs.unlinkSync event at line 90 of node-minify.js can throw an EPERM, operation not permitted error. This happens when the no-compress function is used quickly back to back (as in to concatenate a series of folders of files and then combine them after).
This is occurring on Windows 7 64 bit using the latest version of node.
This feature would be nice.
I am using the 'no-compress' option to just concatenate an array of files, but for large files it often just return a blank string. It works great if I use any compression method. It looks like the problem is on line 113:
var os = _fs.createWriteStream(this.fileOut);
var is = _fs.createReadStream(this.fileIn);
is.pipe(os);
The pipe function runs asynchronously, so the output file ends up being read and returned before it has finished being written.
Hi, I forked your repository and made various modifications. Since the result was not API-compatible with your repository, I made no pull requests and instead published as abridge
on NPM.
However, your users may benefit from some of the API changes.
Thanks for your work
Hi I'm using your module with supervisor and have set up my server to recompile all my js and css when the server reboots due to a file change.
Problem is that your code seems to spit out a lot of temp files and not cleaning them up.
Is there any way you can add a simple -cleanup style parameter to the options so these can be deleted automatically?
Thanks 💃
Writing on fs is slow.
The uglify-js2
npm package should now be installed as uglify-js
since it was re-named. The uglify-js2
package is deprecated. At the moment you'll get uglify-js2 for both the dependencies you list.
I'm using Google Closure Compiler to compress jQuery2.0.0, anyhow I get the following error message:
ERROR: Command failed: src\javascripts\jquery-2.0.0.js:4051: ERROR - Parse error. missing name after . operator
(jQuery.expr.match.boolean.test(name) ? boolHook : nodeHook);
...
Any solution?
new compressor.minify({
type: 'uglifyjs',
fileIn: 'public/js/base.js',
fileOut: 'public/js/base-onefile-uglify.js',
callback: function(err, min){
console.log(err);
// console.log(min);
}
});
After do this,why does't remove comment but only compress the code??
//test( does this comment needn't remove?????)
function(){};
hi man , I use clean-css to minify css files and there are some extra options like 'advanced : false' for compatibility , and i see your source code and find you use the CLI to minify the files , but it does work for me , I wonder if there is a way to solve the issues?
This is even more important I guess than just minify files.
I installed node-minify in a package that already contained minify-js as a dependency, so calling the bin in the relative path to ../node-modules/uglify-js/bin would fail, cause it would live in a different location already
Not sure what the best approach could be for solving this would be - I doubt this is going to be used only in npm scripts, so using devDependencies is probably not a solution, although it would be nice to have a conditional that executes the aliased command when running on npm environment.
The copyright option no longer preserves the copyright at the top of files. I've done some digging and I believe this is why:
A few months ago, uglify-js
on the npm registry was replaced with version 2. Version 2 takes the options after the file name. Version 1 used to take options before the file name.
Your package.json
asks for any version *
of uglify-js
, which is why this now breaks.
Two options to fix it: either specify a version in the package.json
instead of *
or reorder the operations for uglifyjs. If you specified *
as a personal preference, then the obvious choice is to reorder the operations.
I have googled that UglifyJS2 can clean console.log which is supported by node-minify , and I just don't get how to use these options in node-minify, I know it had options property, seems UglifyJS2 use that option property very differently..
var minifiedCode = uglify.minify(originalSourceCode, {
fromString : true,
mangle: {},
warnings: true,
compress:{
pure_funcs: [ 'console.log' ]
}
});
console.log(minifiedCode);
All my scripts are stored in a db and it would be great to minify this texts.
Unfortunately it seems this plugin can only handle files.
I think when starting on debian based systems it trys to run node
as a shell command to compress/minify when on debain/ubuntu systems the command is nodejs
due to a package name clash.
I fixed this by runnning ln -s /usr/bin/nodejs /usr/bin/node
on ubuntu. But I thought you might like to add an attempt to try both commands when the module is running.
When I give array of input files, uglify is not minifying them to single file.
Update Readme and split examples in another file.
new compressor.minify({
type: 'uglifyjs',
fileIn: ['file1.js', 'file2.js' ],
fileOut: 'file.min.js',
callback: function(err, min){}}
);
Gives error: 'Path must be a string', seems to originate from the following code in node-minify line 29
if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type !== 'gcc') {
var out = options.fileIn.map(function(path) {
return _fs.readFileSync(path, 'utf8');
});
_fs.writeFileSync(this.tempFile, out.join('\n'), 'utf8');
this.fileIn = this.tempFile;
} else if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type === 'gcc') {
this.fileIn = options.fileIn;
}
I guess the condition should be updated to include uglifyJs as well:
if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type !== 'gcc' && options.type !== 'uglifyjs' )
and:
else if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && (options.type === 'gcc' || options.type === 'uglifyjs' ))
I'm keen to use this on launch of my server to hold a concatenated and minified version of my client app for serving.
For various reasons, I'd like to not save this first and just have it returned as a string as this will save me two file operations on launch.
Any feasibility in doing this?
Many thanks!
Updating from 1.1.0 -> current broke a custom build tool I've been using. It has to do with this line glob syncing from the current working directory. It should be searching for "**/.bin" relative to __dirname. I'm on deadline right now so I can't fix this for you, currently just reverting to 1.1.0.
may be you should be checking for entire directory instead of just __dirname + '/../node_modules something like below .
var getPath = function(bin) {
nodeModulesV2 = path.normalize(__dirname + '/../node_modules/'+bin);
isNPMv2 = dirExistsSync(nodeModulesV2);
dirToScan = isNPMv2 ? nodeModulesV2 : '';
var binPath = glob.sync(dirToScan + '**/.bin/' + bin +
((platform === 'win32') ? '.cmd' : ''), {realpath: true})[0];
console.log(binPath);
if (!binPath) {
throw new Error(bin + ' not found !');
}
return binPath;
When I do,
// Using UglifyJS for JS
new compressor.minify({
type: 'uglifyjs',
fileIn: 'public/js/base.js',
fileOut: 'public/js/base-onefile-uglify.js',
callback: function(err){
console.log(err);
}
});
It did not minify file. It was able to minimise when I replaced the command in node-minify with following. I have removed quotes around uglifyjs.
case 'uglifyjs':
command = prefix + __dirname + '/../node_modules/uglify-js/bin/uglifyjs --output "' + this.fileOut + '" ' + (this.copyright ? '' : '--no-copyright') + ' "' + this.fileIn + '" ' + this.options.join(' ');
Hi, I'm having this error a lot using the plugin, it's easy to solve, but it would be great if node-minify could handle this, and create the output file -- including the directory.
andvarp
How can caching be implemented ?
This happened occasionally while I was using uglifyjs. I added two console.log
statements in node-minify.js
one was after tempFile
was set in minify
function, the other was just before the deletion code. And I found in some cases the temp file name was the same for two node-minify
instances. I think this is because you generate the file name based on current time but in some cases it runs fast so that two tem files would have the same name. So when you tried to delete the second minify will raise error as the temp file had been deleted by the one before. How about using uuid
to generate temp files.
https://github.com/srod/node-minify/blob/master/lib/node-minify.js#L100
The hard coded paths linked above do not work with npm 3.x since it flattens out all dependencies to reduce nesting.
Just to be aware: currently node-minify might be unable to process full paths on Windows correctly because of this bug:
yui/yuicompressor#78
I spent almost an hour debugging the issue until I came to that bug. I guess, it would be better to revert to 2.4.7 until they fix the issue.
Or you could try to create a workaround - writing to a temp file in relative path and then back to the final target.
Found on windows - i suspect if multiple instances of minify is used concurrently - an error is thrown in some cases :
e.g.
events.js:72
throw er; // Unhandled 'error' event
^
Error: ENOENT, open 'E:\apps\Atajo-Lims\server\1418288361318-7115bbef-e515-4213-a513-36121e88f381'
Resolved by changing line 121 of node-minify.js to async unlink - e.g.
_fs.unlink(self.tempFile, function(err) {
if(err) { console.log("UNLINK ERROR : "+err); }
else { }
});
I updated to 1.3.0 and now I see below error.
C:\XYZFolder\node_modules.bin\uglifyjs:2
basedir=dirname "$0"
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
] killed: false, code: 8, signal: null }
ui-core compression error: { [Error: Command failed:
C:\XYZFolder\node_modules.bin\sqwish:2
basedir=dirname "$0"
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
] killed: false, code: 8, signal: null }
Hi,
I need to use node-minify in a project, but it only calls asynchronous execution of child processes to do the actual minification work. This is an issue for me, since in my code structure I need it to be done synchronously.
Is it possible to support something like a {sync: true}
option, defaulting to false
, so that it's run synchronously when the client code requests it?
I have an idea and am curious to see what others think.
Take this block for example:
new compressor.minify({
type: 'uglifyjs',
fileIn: [
'public/bower_components/angulartics/dist/angulartics.min.js',
'public/bower_components/angulartics/dist/angulartics-google-analytics.min.js',
'public/bower_components/angulartics/dist/angulartics-segmentio.min.js'
],
fileOut: 'public/js/scripts.js',
callback: function(err, min){
console.log(err);
}
});
I would like to pass an extra argument to the callback, that will return a string that looks like:
<script src="bower_components/angulartics/dist/angulartics.min.js"></script>
<script src="bower_components/angulartics/dist/angulartics-google-analytics.min.js"></script>
<script src="bower_components/angulartics/dist/angulartics-segmentio.min.js"></script>
That way, when I'm in my .ejs template I can do something like <%= nonMinified => which will inject the premade string if I'm running on development.
Hi srod,
I'm trying to implement this pretty asynchronous minifier,
I've downloaded it, required it, but the minify function always give me back the error arg, and it doesn't work.
I'm working on a node-webkit app on a windows system (the app is supposed to be available on Linux / Mac / Windows).
And I call the minifier in this way :
var minifier = require('node-minify');
[...]
new minifier.minify({
type: 'uglifyjs',
fileIn: ["C:\Users...\main.js", ...],
fileOut: "C:\Users...\app.min.js",
buffer: 1000 * 1024,
callback: function (e) {
console.log('callback error', e);
}
});
The full error object is :
Error {
killed: false,
code: 1,
signal: null
}
I was asking myself if it was caused by the absolute filepaths, but I do not have the choice, because I am working on a new created folder (created with fs.mkdirSync...).
I've tried both linux-style and windows-like filepaths (C:... and C:/...).
I create the output file and it is working, but it do not put the minified content on it.
Do you have an idea ?
Can you change in "libs/node-minifiy.js" the line:
var prefix = (platform === 'win32') ? 'node ' : process.argv[0] + ' ';
to
var prefix = (platform === 'win32') ? '"' + process.argv[0].replace(/\\/g,'/') + '" ' : process.argv[0] + ' ';
If node.js is not installed, "node" on cmd can not be found!
This issue is back again with the changes made in 256e861#comments
As a user I would like to minify all the files from a selected folder using paths like:
fileIn: ['html/js/*/.js']
Any way to send gcc additional flags? I'd like to have gcc create source maps.
in my situation , java-based compressor is not sutable ( java process handleing is not stable so my compilation sometimes incomplete), so I wish you could also embed a Javascript-written css compressor in your lib. e.g. https://github.com/ded/sqwish .
BTW, your minifier is amazing 👍
I've had trying to run minify under Windows .. perfect ... but on Linux (Ubuntu 14.04) it´s not working if i use yui-css, sqwish or uglifyjs. On "no-compress" everything works perfect.
I'm haivng issues where yui-js is not working. It looks like running this via grunt the 'child_process' is not working.
If I try to node-js as a cluster, I get intermittent file i/o errors in node-minify. It's kind of odd, because I wait until minify has completed before I start up the cluster via callback. The error I see is:
fs.js:760
return binding.unlink(pathModule._makeLong(path));
^
Error: ENOENT, no such file or directory './tmp/1394491036813'
at Object.fs.unlinkSync (fs.js:760:18)
at /Users/jeff.l/Documents/workspace/maverickUX/node-js/node_modules/node-minify/lib/node-minify.js:104:25
at ChildProcess.exithandler (child_process.js:641:7)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:735:16)
at Socket. (child_process.js:948:11)
at Socket.EventEmitter.emit (events.js:95:17)
at Pipe.close (net.js:466:12)
worker 74524 died
var http = require('http')
,cluster = require('cluster')
,minify = require('./minify.js')
;
...
var launchServices = function() {
var numCPUs = require('os').cpus().length;
if (isCluster && cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs/2; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}
else {
var port = parseInt(config['port']);
server.listen(port);
}
}
minify({compress: isCompress}, launchServices);
I'm using node-minify 0.9.1, cluster 0.7.7
When I use nodemon, it is restarting repeatedly.
I created ".nodemonignore" file, then i added "/static/minified.js" line in this file.
But nodemon detects node-minify temp file.
EDIT : When i change temp file location, it's corrected.
Any way to track file system changes and than compress js again?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.