write html content into word and download in user machine using node.js - node.js

How to use html-docx-js in node.js .
I have refered the npm site (https://www.npmjs.com/package/html-docx-js) for this. Below is the code
var converted = htmlDocx.asBlob(content);
saveAs(converted, 'test.docx');
But here is the problem, the saveAs function is missing in the tutorial.
I have downloaded filesaver.js on the client side i Iave implemented this and it works fine. But I want complete code in node.js running which it will convert my html content and will download a word file in client machine.
Looking forward for some help.
Regards,
Bikram Nayak.

var HtmlDocx = require('html-docx-js');
var fs = require('fs');
var html = 'fasfasfasdfsfsdfsf';
var docx = HtmlDocx.asBlob(html);
fs.writeFile('helloworld3.docx',docx, function (err){
if (err) return console.log(err);
console.log('done');
});

Related

Unable to use res.send and res.download in Node/Express due to headers already being set

I am new to Node, and I am trying to make it so that when I go to 'localhost:1337/download/open' it renders a webpage, as well as download a file.. I understand that you can only set a header once (that is the error I am getting), but what is the easiest way to both render html AND download a file? Code below:
const express = require('express');
const app = express();
app.get('/download/open', function (req, res) {
let file = `${__dirname}/downloads/Open Tasks.csv`;
res.download(file);
res.send("words");
})
app.listen(1337, function (err) {
if (err) {
console.log(err)
return
}
console.log(`App running. listening on: http://localhost:1337`);
});
Error:
Error: Can't set headers after they are sent.
Thank you in advance.
I was able to figure out what I was trying to do. Instead of trying to render a whole new page AND download a file, I needed to dedicate a route to just a download through the use of an <a></a> tag.
For instance, if I have a webpage at 'http://localhost:1337' that has a link on it like:
Download Open Tasks
Download Open Tasks
Then in node.js I have a route for 'download/open' like so:
app.get('/download/open', function (req, res) {
let file = `${__dirname}/downloads/Open Tasks.csv`;
res.download(file);
})
It will not open a new page (like I thought it needed to) it will just download the file.
IMO, I would suggest you should do the following to achieve your goal:
render the HTML result for "GET http://localhost:1337/download/open"
In the HTML file /download/open, put AJAX block to invoke download file operation
(Download a file by jQuery.Ajax)
$(document).ready(function(){
//code to invoke download file....
});

Node.js reads the file but does not write JSON in the HTML

I'm currently running Node.js by Browserify for my website.
It reads the JSON file and I get the message through MQTT.
But the problem is that it seems like writefile does not work.
(Running this as node test.js in the terminal works by the way).
What is wrong with my code?
Moreover, Is this the best way to store any user data?
Thank you so much in advance.
Here's some part of my code
var fs = require("fs");
var path = require("path");
let newFile = fs.readFileSync('/home/capstone/www/html/javascript/test.json');
function testT() { //THIS WORKS FINE
let student0 = JSON.parse(newFile);
var myJSON = JSON.stringify(student0);
client.publish("send2IR", myJSON);
response.end();
};
function write2JSON() { //PROBLEM OF THIS CODE
const content = 'Some content!'
fs.writeFileSync('/home/capstone/www/html/javascript/test.json', content)
};
document.getElementById("blink").addEventListener("click", publish);
document.getElementById("write").addEventListener("click", write2JSON);
You cann't write directly for security reasons. For other hand you can use a server as API to do the filye system tasks and in the client only trigger the events.
This post is very related with your problem:
Is it possible to write data to file using only JavaScript?

Small api on node.js

maybe someone have example for creating small API on node.js
Example, i have function this function will return string
I need call this string from postman or inside any another project with http.
What better for create this API?
Maybe someone know good guide? I worked before with node.js only like web-server
It is best practice that building API's in nodejs with express.Here is a code in which function returns a string. You need to export it. And require the file that contains exported value in your project file with the file path. Here is my function code where I am returning a string value. func.js
var string;
function myfunc(param,callback){
var str="hello";
callback(null,str);
}
myfunc('aaa',function(err,result){
if(err){
console.log(err);
}
else{
exports.string=result;
}
});
Here is my routes file and here I am calling the string from func.js and I named this file as str.js
var http = require('http');
var express = require('express');
var main = require('./func.js');//path of file
var org = main.string;
var app = express();
app.get('/str',function(req,res){
console.log(org);
res.send(org);
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
Run the code as node str.js and in postman run the url as http://localhost:3000/str and you can see the returned string in both response and in terminal.
Hope this helps...
This tutorial shows you how to build an API in Node.js with Express.
EDIT: You can skip the database part if you don't need it.

Error while zipping a folder using Easyzip

Using Easyzip I am trying to zip a folder along with its files. The below mentioned code is not working properly. I get an error 'error occurred while extracting files'. Is there any other method to zip a folder with all its files and subfolders?
Here is my back-end code :-
var zip2 = new EasyZip();
zip2.zipFolder('./downloads/'+application._id,function(){
zip2.writeToFile('./downloads/'+application._id+'.zip');
res.setHeader('Content-disposition', 'attachment; filename='+application._id+'.zip');
res.setHeader('Content-type', 'application/zip');
var fs = require('fs');
var filestream = fs.createReadStream('./downloads/'+application._id+'.zip');
filestream.pipe(res);
});
});
My angular.js code
$http.post('/download/archive/' + stateParams._id, {year: year}).success(function (data) {
var file = new Blob([data], {type: 'application/zip'});
console.log(file)
saveAs(file, 'application.zip');
});
Please help me to solve these. Thanks in advance.
Even I had the same problem and was able to solve it. For more details check: Zip generated by EasyZip is not working properly Hope that this may help you.

Generate static HTML files from ejs templates

OK, so I have my basic nodejs website up and running. It's all working and runs through a node server - using my basic-node-site
It uses ejs as the templating engine.
I'd like to release these templates as a static website. So all generated locally and it exports all my pages to static HTML files that I can publish on my basic hosting platform. no server side technology required.
I've had a look at jade, but it required me to change the templating and the structure.
Is there any tool out there that just publishes my current setup to a folder with all the generated html files??
Thanks for any help. It's appreciated.
As long as you have the EJS npm package installed you can compile it.
var fs = require('fs'),
ejs = require("ejs");
function ejs2html(path, information) {
fs.readFile(path, 'utf8', function (err, data) {
if (err) { console.log(err); return false; }
var ejs_string = data,
template = ejs.compile(ejs_string),
html = template(information);
fs.writeFile(path + '.html', html, function(err) {
if(err) { console.log(err); return false }
return true;
});
});
}
ejs2html(__dirname+"/index.ejs")
Path: the location of the file, include __dirname or it wont work
Information: the information to be compiled like {users: ['bill','bob']} (optional)
EJS
Reading file in NodeJS
Edit
I made the code work and tested it, the ejs file will be compiled and written to the same directory with .html appended to the end.

Resources