This is the code written by me to get all the js files in a directory to be minified:
var http = require('http');
var testFolder = './tests/';
var UglifyJS = require("uglify-js");
var fs = require('fs');
var glob = require("glob");
var fillnam="";
hello();
function hello()
{
glob("gen/*.js", function (er, files) {
//console.log(files);
for(var i=0;i<files.length;i++)
{
fillnam=files[i];
console.log("File Name "+fillnam);
fs.readFile(fillnam, 'utf8', function (err,data)
{
if (err) {
console.log(err);
}
console.log(fillnam+" "+data);
var result = UglifyJS.minify(data);
var gtemp_file=fillnam.replace(".js","");
console.log(gtemp_file);
fs.writeFile(gtemp_file+".min.js", result.code, function(err) {
if(err) {
console.log(err);
} else {
console.log("File was successfully saved.");
}
});
});
}
});
}
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
As a result respective minified js files with same name with .min.js should be formed in the same directory.
But what I am getting is a single file with all files data over written. Like for example if there are two files in a directory a.js and b.js with content:
var a=10;var b=20;
var name="stack";
What I'm getting is single file a.min.js with file content:
var a=10tack;
Please help.
You need to collect all file contents first, concat them and then run UglifyJS.minify on them to be able to save it as a single file.
Something like this (not fully tested)
const testFolder = './tests/';
const UglifyJS = require("uglify-js");
const fs = require('fs');
const readFile = require('util').promisify(fs.readFile);
const glob = require("glob");
function hello() {
glob("gen/*.js", async(er, files) {
let data = [];
for (const file of files) {
const fileData = await readFile(file, {
encoding: 'utf-8'
});
data.push(fileData);
}
const uglified = UglifyJS.minify(data.join('\n'));
fs.writeFile('main.min.js', uglified);
});
}
hello();
Related
I am using fs mudule to read .txt file content , but the result always empty . My .txt file do has content in it could any one give me a hand pls ? This is my test code :
var fs = require("fs");
var content = "";
fs.readFile("2.txt", "utf8", function(err, data){
if(err) {
return console.log("fail", err);
}
content = data;
});
console.log(content);
The content is empty in console .
You are writing the result too early. You should log the result in the readFile callback.
var fs = require("fs");
var content = "";
fs.readFile("2.txt", "utf8", function(err, data){
if(err) {
return console.log("fail", err);
}
content = data;
console.log(content);
});
// The console log below will be executed right after the readFile call.
// It won't wait the file to be actually read.
// console.log(content);
Or you can write the same logic like this:
const fs = require('fs');
async function main() {
try {
const content = await fs.promises.readFile('2.txt', 'utf8');
console.log(content);
} catch (ex) {
console.trace(ex);
}
}
main();
I have created a file called config.js which looks like below:
const config = {
staticFiles:{
name:[
'./',
'./index.html',
'./script.js',
'./icon.jpg'
]
},
outputFolderName: "D:\\DemoApp",
sourceApplicationParentPath: "D:\\DemoApp\\"
};
Now I am reading list of files from sourceApplicationParentPath folder using node and have to update staticFiles array of above file. I am not sure how should I do it. Can someone please help.
Thanks in advance.
config.js
const config = {
staticFiles: {
name: ['./',
'./index.html',
'./script.js',
'./icon.jpg',
]
},
outputFolderName: 'D:\\DemoApp',
sourceApplicationParentPath: 'D:\\DemoApp'
};
module.exports = config;
index.js
var fs = require('fs'),
config = require('./config'),
util = require('util');
fs.readdir(config.sourceApplicationParentPath, function(err, files) {
if (err) console.log(err.message);
for (var i = 0; i < files.length; i++) {
if (config.staticFiles.name.indexOf(`./${files[i]}`) == -1) {
config.staticFiles.name.push('./' + files[i]);
}
if (i == (files.length - 1)) {
var buffer = `const config = \n ${util.inspect(config, false, 2, false)}; \n module.exports = config;`;
fs.writeFile('./config.js', buffer, function(err) {
err || console.log('Data replaced \n');
})
}
}
});
The Above code is tested and working fine.
You can add or change the object or an array or value in config.js without duplicate entry.
config.js
const config = {
staticFiles:{
name:[
'./',
'./index.html',
'./script.js',
'./icon.jpg'
]
},
outputFolderName: "D:\\DemoApp",
sourceApplicationParentPath: "D:\\DemoApp\\"
};
exports.config = config;
code for the file from where you want to change the data
var fs = require('fs');
var bodyparser = require('body-parser');
var config = require('./config.js')
//path of directory
var directoryPath = "D:\\DemoApp\\"
var data = config.config;
//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
var dataToUpdate = data.staticFiles.name;
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
console.log(file)
dataToUpdate.push(file)
});
data.staticFiles.name = dataToUpdate;
var value = 'const config = ' + JSON.stringify(data) + ';' + '\n' + 'exports.config = config';
fs.writeFile('./config.js',value, er => {
if(er){
throw er;
}
else{console.log('success')}
});
});
I want to upload files of my form to my server.
I have already test this but i haven't a success.
What is the best npm module for that ?
Can i test it in localhost ?
Thanks
For Express Use,
https://www.npmjs.com/package/multer
For Hapi.js
https://gist.github.com/joyrexus/0c6bd5135d7edeba7b87
Hope This Helps!
Using Hapijs
I have done Image upload in one of my projects
I had Used Nginx to define my root location for this file upload.
var mkdirp = require('mkdirp');
var path = require('path');
var mv = require('mv');
exports.imageUpload = function (req, reply) {
var payload = req.payload;
commonImageUpload(payload.uploadFile,urid,function(err,res){
});
}
var commonImageUpload = function (file, idUser, callback) {
if (null != file) {
var extention = path.extname(file.filename);
var extentionsList = [];
extentionsList.push('.jpg');
extentionsList.push('.png');
extentionsList.push('.jpeg');
extentionsList.push('.gif');
var index = extentionsList.indexOf(extention.toLowerCase());
if (index < 0) {
callback(true,"Invalid Media Type");
} else {
var filepath;
filepath = '../cdn/idcard/';
var fname = filepath + idUser + extention;
console.log(fname);
mkdirp(filepath, function (err) {
if (err) {
console.log(err);
callback(true,"Internal Server Error");
}
else {
mv(file.path, fname, function (err) {
});
}
});
}
} else {
callback(true);
}
}
Let me know if this solves your problem.
I'm trying to concatenate multiple files and save to a new file using node js createWriteStream and createReadStream. I have a small bug that I would like to print out the file name before its contents. However, the file name is always printed on top of the output file. Please see my result output and if you have any ideas why, please help!
Thanks!
test.js
var async = require('async');
var fs = require('fs');
var path = require('path');
var SOURCE_FOLDER = '/tmp/test';
var SOURCE_FILE_PATTERN = /\.json$/
var REPORT_FILE = path.join(SOURCE_FOLDER, 'output.html');
var writeStream = fs.createWriteStream(REPORT_FILE, {
flags: 'w',
encoding: 'UTF-8'
});
var appendReport = function appendReport(file, callback) {
var readStream = fs.createReadStream(file, {
flags: 'r',
encoding: 'UTF-8'
});
readStream.pipe(writeStream, {
end: false
});
readStream.on('end', callback);
};
fs.readdir(SOURCE_FOLDER, function (err, files) {
if (err) {
console.log(err);
} else {
writeStream.write("<html><body><pre>\n");
async.forEach(files, function (file, callback) {
var filePath = path.join(SOURCE_FOLDER, file);
fs.stat(filePath, function (err, stats) {
if (err) {
callback(err);
} else if (stats.isFile() && file.match(SOURCE_FILE_PATTERN)) {
writeStream.write("\n" + filePath);
appendReport(filePath, callback);
} else {
callback();
}
});
}, function (err) {
writeStream.write("\n</pre></body></html>");
});
}
});
My Current Result:
# node test.js; cat /tmp/test/output.html
<html><body><pre>
/tmp/test/a.json
/tmp/test/b.jsoncontent A
content B
</pre></body></html>
My Expected Result:
# node test.js; cat /tmp/test/output.html
<html><body><pre>
/tmp/test/a.json
content A
/tmp/test/b.json
content B
</pre></body></html>
The problem is that async.forEach === async.each and async.each() calls the iterator in parallel. What you want is async.eachSeries() instead.
I'm using Node.js and trying to render an EJS template file. I figured out how to render strings:
var http = require('http');
var ejs = require('ejs');
var server = http.createServer(function(req, res){
res.end(ejs.render('Hello World'));
});
server.listen(3000);
How can I render an EJS template file?
There is a function in EJS to render files, you can just do:
ejs.renderFile(__dirname + '/template.ejs', function(err, data) {
console.log(err || data);
});
Source: Official EJS documentation
var fs = require('fs');
var templateString = fs.readFileSync('template.ejs', 'utf-8');
and then you do your thing:
var server = http.createServer(function(req, res){
res.end(ejs.render(templateString));
});
All you have to do is compile the file as a string (with optional local variables), like so:
var fs = require('fs'), ejs = require('ejs'), http = require('http'),
server, filePath;
filePath = __dirname + '/sample.html'; // this is from your current directory
fs.readFile(filePath, 'utf-8', function(error, content) {
if (error) { throw error); }
// start the server once you have the content of the file
http.createServer(function(req, res) {
// render the file using some local params
res.end(ejs.render(content, {
users: [
{ name: 'tj' },
{ name: 'mape' },
{ name: 'guillermo' }
]
});
});
});
#ksloan's answer is really good. I also had the same use case and did little bit of digging. The function renderFile() is overloaded. The one you will need mostly is:
renderFile(path: string,data, cb)
for example:
ejs.renderFile(__dirname + '/template.ejs', dataForTemplate, function(err, data) {
console.log(err || data)
})
where dataForTemplate is an object containing values that you need inside the template.
There's a synchronous version of this pattern that tightens it up a little more.
var server = http.createServer(function(req, res) {
var filePath = __dirname + '/sample.html';
var template = fs.readFileSync(filePath, 'utf8');
res.end(ejs.render(template,{}));
});
Note the use of readFileSync(). If you specify the encoding (utf8 here), the function returns a string containing your template.
The answer of #ksloan should be the accepted one. It uses the ejs function precisely for this purpose.
Here is an example of how to use with Bluebird:
var Promise = require('bluebird');
var path = require('path');
var ejs = Promise.promisifyAll(require('ejs'));
ejs.renderFileAsync(path.join(__dirname, 'template.ejs'), {context: 'my context'})
.then(function (tpl) {
console.log(tpl);
})
.catch(function (error) {
console.log(error);
});
For the sake of completeness here is a promisified version of the currently accepted answer:
var ejs = require('ejs');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
fs.readFileAsync(path.join(__dirname, 'template.ejs'), 'utf-8')
.then(function (tpl) {
console.log(ejs.render(tpl, {context: 'my context'}));
})
.catch(function (error) {
console.log(error);
});
Use ejs.renderFile(filename, data) function with async-await.
To render HTML files.
const renderHtmlFile = async () => {
try {
//Parameters inside the HTML file
let params = {firstName : 'John', lastName: 'Doe'};
let html = await ejs.renderFile(__dirname + '/template.html', params);
console.log(html);
} catch (error) {
console.log("Error occured: ", error);
}
}
To render EJS files.
const renderEjsFile = async () => {
try {
//Parameters inside the HTML file
let params = {firstName : 'John', lastName: 'Doe'};
let ejs = await ejs.renderFile(__dirname + '/template.ejs', params);
console.log(ejs);
} catch (error) {
console.log("Error occured: ", error);
}
}