2

I have tried to minify javascript files using uglifyjs into one file, but it's not working. I used $node uglifyjs.js to run the file. Below is the code in uglify.js

  var fs = require('fs');

  var uglifyjs = require('uglify-js');

  var files = ['app.js', 'geolocation.service.js'];

  var result = uglifyjs.minify(fs.readFileSync(files, 'utf8'));

 console.log(result.code);

 fs.writeFile("output.min.js", result.code, function(err){
 if(err){
  console.log(err);
  } else {
  console.log("File was successfully saved.");
 }
 });

When I run this code I get the following error message:

  fs.js:549
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), 
  mode);
             ^

   TypeError: path must be a string
   at TypeError (native)
   at Object.fs.openSync (fs.js:549:18)
   at Object.fs.readFileSync (fs.js:397:15)
   at Object.<anonymous> (C:\Users\HP\Desktop\uglify\uglify.js:7:33)
   at Module._compile (module.js:435:26)
   at Object.Module._extensions..js (module.js:442:10)
   at Module.load (module.js:356:32)
   at Function.Module._load (module.js:311:12)
   at Function.Module.runMain (module.js:467:10)
   at startup (node.js:134:18)
1
  • fs.readFileSync(file[, options]) -- file <string> | <Buffer> | <integer> filename or file descriptor Commented May 26, 2017 at 1:10

1 Answer 1

4

As shown here, uglify.minify requires that you pass in a string or a list of strings.

Your code:

var result = uglifyjs.minify(fs.readFileSync(files, 'utf8'));

Is trying to read several files at once, but fs.readFileSync only accepts one file.

So change your code to this:

var filesContents = ['app.js', 'geolocation.service.js'].map(function (file) {
    return fs.readFileSync(file, 'utf8');
})

var result = uglifyjs.minify(filesContents);

if (result.error) {
    console.error("Error minifying: " + result.error);
}

fs.writeFile("output.min.js", result.code, function (err) {
    if (err) {
        console.error(err);
    } else {
        console.log("File was successfully saved.");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. That totally did the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.