How to save a file to the public folder

162 views
Skip to first unread message

bobfr...@googlemail.com

unread,
Jul 11, 2016, 5:40:09 AM7/11/16
to NodeChef
I'm using a module to generate a pdf file from some html. But I'm a newbie and cannot get the file to save into the public folder so I can access it using the web browser...? My best guess was [../public/businesscard.pdf] but thats not working! Thanks

==============
var pdf = require('./node_modules/html-pdf');
var html = '<h1>Hi there!</h1>';

pdf.create(html, options).toFile('../public/businesscard.pdf', function(err, res) {
  if (err) return console.log('we got error writing pdf file');
  console.log('looking good for pdf file');
});

in...@nodechef.com

unread,
Jul 11, 2016, 8:00:42 PM7/11/16
to NodeChef, bobfr...@googlemail.com
You have to know the structure of the folder of your app. The root directory of your app is in /bundle. To also get the executing location of any module you can use the nodejs global variable __dirname as in: var current_module_directory = __dirname.

Another way to also do this is to save the file to the /tmp folder and then read it from there when the request is received.

bobfr...@googlemail.com

unread,
Jul 12, 2016, 2:51:45 AM7/12/16
to NodeChef, bobfr...@googlemail.com, in...@nodechef.com

Thanks. I have migrated over from the Parse platform and have an App working great. But am new to server side development environment. Here is the basic structure...

root:
-[cloud]: main.js running from here, and want to save file to the public folder
-[public]: the website access point for index.html, about.html etc

So I need to go up the folder tree one level I would think in order to then target [public]. But ../ does not seem to work.

Thanks
Bob

bobfr...@googlemail.com

unread,
Jul 12, 2016, 3:33:43 AM7/12/16
to NodeChef, bobfr...@googlemail.com, in...@nodechef.com
SOLVED IT!!!

Thanks, I have done my homework and realised how to fix... thanks for the lead in right direction
========
var options = { format: 'Letter' };
var current_module_directory = __dirname;
var public_folder_directory = '/../public';

app.use(express.static(public_folder_directory));

var html = fs.readFileSync(current_module_directory + '/businesscard.html', 'utf8');

pdf.create(html, options).toFile(public_folder_directory + '/businesscard.pdf', function(err, res) {
  if (err) return console.log('we got error writing pdf file');
  console.log('looking good for pdf file');
  console.log(res); // { filename: '/app/businesscard.pdf' } 
});
===========
Reply all
Reply to author
Forward
0 new messages