Save HTML table data to a csv file with custom file path - javascript

I am currently writing an app using electron, and I'm trying to save the contents of a Html table to a CSV file.
I tried this, in this way:
let $ = require('jquery')
let fs = require('fs')
var dialog = require('electron').remote.dialog
$('#save-file').on('click', () => {
dialog.showSaveDialog({ filters: [{ name: 'csv', extensions: ['csv'] }]}, function (fileName) {
if(fileName === undefined){
console.log("Please give a file name!");
}else{
var value = $('#data-table').TableCSVExport({delivery:"value"})
fs.writeFile(fileName, value, function (err) {
});
}
});
})
It almost satisfy my needs, except for the data are all surrunded by "", which is not what I want.
Then I saw this. There are tons of similar ones like this, but they all download automatically once you click the button.
What I want is when the button gets clicked, it will show up a dialog box to let the user select a file path, then save the file to that position.
Also, I only need the tr(data) to be saved, so exclude the th(headings)
Is there any js library can satisfy my needs?
Appreciated for any guidance!

If you are looking to have a user pick their own file location, then the following code is an example of the showSaveDialog method using the csv-write-stream npm package. This is a code snippet and not a copy/paste fully working example. The relevant item is the file function plus dependencies:
const { dialog } = require('electron');
const fs = require('fs');
const csvWriter = require('csv-write-stream');
function saveFile(){
const folderLocation = dialog.showOpenDialog({
title:"Select Save Location",
properties: ["openDirectory"]
});
let writer = csvWriter()
writer.pipe(fs.createWriteStream(folderLocation))
writer.write({hello: "world", foo: "bar", baz: "taco"})
writer.end()
};
You should have the option either way, with showOpen or showSave, to navigate the file structure to pick a folder.
In reference to the handling of csv files, check the following npm packages:
csv-write-stream
csv
fast-csv
Another cool package for handling CSVs is handsOnTable for displaying them in your electron app with the look of an excel doc.

Related

Questions about fs.writeFile

I want to use fs.WriteFile in my JS project. I am building an algorithm that outputs random data and I want to give the user the opportunity to save the data as a txt file. I have been able to implement fs.WriteFile in my project, but I have a couple of questions on how to proceed next as the function remains somewhat unclear.
How do I specify that I want to include the contents of various vars? Is it as simple as data = let1 + let2 + let3 and all of the data will be included?
can I add the current date and time in the .txt file name? If so, how?
How do I tell writeFile to save the contents to a .txt file and open a download blob so that people can specify their own download locations?
Thanks in advance!
I've tried looking at basic documentation but its mainly the same: a template using a simple string that saves into the same directory, which is what I don't want.
For you first question, you are correct. You can just combine different string variables into a larger string variable. See the documentation for string concatenation for more information.
For your second question, yes you can. You can get the current date and time with new Date() and turn it into a variety of formats. For file names, using mydate.toISOString() will probably be the most clean.
Here's an example of both of these in practice:
import fs from 'fs';
// Here's some data that we want to put in the file.
const name = "Bob";
const age = 43;
// Create the data we want to put in our file.
const data = name + '\n' + age;
// Let's grab the date and use it as part of our file name.
const date = new Date();
const fileName = `${date.toISOString()}.txt`;
// Call fs.writeFile to put the data in the file.
fs.writeFile(fileName, data, () => {
console.log(`Wrote data to ${fileName}.`);
});
Your third question is more complicated and probably worth a separate post. fs.writeFile can't do this for you. You'll have to come up with some mechanism for the user to enter their own file name and build off of that.
Edit:
To address your question in the comments, you might be a little confused with how NodeJS works. NodeJS runs on the server and doesn't have any way to deal with buttons or UIs by default like browser JavaScript does. It might be helpful to look at the differences between the two. So you won't be able to save it to the downloads folder on a button click.
With that said, we can save the file to the user's Downloads folder with the same script I posted above by adding the path to the Downloads folder to the beginning of the file name.
Here's the code above adjusted to do that:
import fs from 'fs';
import os from 'os'; // NEW
import path from 'path'; // NEW
const name = "Bob";
const age = 43;
const data = name + '\n' + age;
const date = new Date();
const fileName = `${date.toISOString()}.txt`;
// Get the user's home directory.
const homedir = os.homedir();
// Append the Downloads directory and fileName to the user's home directory.
const fullPath = path.join(homedir, 'Downloads', fileName);
// Use fullPath here instead of fileName.
fs.writeFile(fullPath, data, () => {
console.log(`Wrote data to ${fileName}.`);
});

How to make a pdf from MongoBD Binary with File API?

I would like some help to make a File object from a pdf stored in MongoDB.
I am not using GridFS, the file is stored as such:
File structure in MongoDB
I am using this function to make the File:
const handlegetfile = () => {
API.getFile(2).then((result) => {
console.log(result.data);
const file = new File(Uint8Array.from(result.data.File.data), result.data.File.name);
console.log(file);
API.writeFile({
CodeTiers: "2525",
Type: { value: "non", label: "testfile" },
Format: "pdf",
File: file,
});
});
};
The .pdf file created by the writeFile() function can't be opened, and when opened with an editor, it looks like this:
pdf data after retrieved
Important: I do not want to write the file to the disk, writeFile() is just here to be sure that the pdf can be opened.
The thing is: the data goes from this in the original file:
original pdf data
To this in MongoDB:
data in MongoDB
To what is in the second screenshot. I am pretty sure the problem comes from the cast to a Uint8array but I can't find what else to use there for it to work. I tried exploding the response with {...result.data.File} and using an ArrayBuffer, also by simply casting to an array new File([result.data.File.data], result.data.File.name) but I couldn't get it to work either way.
Could you help me please ?

Is there a way to save/write a text file in the renderer process without opening the dialog box in VueJs?

Hey i am working in this project(app) based on VueJs + electron and trying to save a text file to the user pc but i don't want any prompt or dialog box to pop up .Is there a way to achieve this ?Note that i know how to do it using require('fs') but fs does not work inside renderer process.So i am trying to use a different method .Currently i am using require('file-saver') but the problem is it is also opening a dialog box asking where to save the file.I want that the file be saved wherever(except the root directory obviously)i want it to by specifying the path.PS:I know that there are security reasons so browser cant directly save the file.But the thing is i have 100s of files that i want to save and i don't want the user to click ok for each file.The code that i am using is as below:
methods:
{
uploadClicked:function(){
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");
}
}
What if you try to send the string to the main process and use fs from their?
In your renderer process
const { ipcRenderer } = require('electron')
//#2
//Pass argument
ipcRenderer.send('save-file', options);
In your main process
const { ipcMain } = require('electron')
const fs = require('fs')
ipcMain.on('save-file', (ev, options )=>{
//try save with fs
fs...
// send notifications after save
ev.reply()
})

Creating a PDF and moving it to a directory?

I am using PDFMake to create a PDF file, the body of which is dynamic. When I create the PDF it downloads to my downloads folder.
I would love for the PDF to be able to save to a directory of my choice. I have looked through the PDFMake docs and all I can see is that it gives you the option to give it a custom name. Does anyone know how I can make this happen. I don't want to just retrieve it from the folder it's in because it could possibly be in a different folder depending on the user.
Below is the code where I create the PDF:
function createPDF() {
let body = tinymce.get('elm1').getContent();
let docDefinition = {
content: body
};
console.log(body);
pdfMake.createPdf(docDefinition).download();
}
Example:
let fs = require('fs');
let PdfPrinter = require('pdfmake');
let printer = new PdfPrinter();
let docDefinition = {
content: .....
};
pdf = printer.createPdfKitDocument(docDefinition);
pdf.pipe(fs.createWriteStream('YOUR-PDFs/YOUR-PDF.pdf'));
pdf.end();

node-webkit - reading data stored in json editing and saving

I am making a program in nwjs, which will be used to reading part of .json file and showing it + giving possibility to edit it.
And I don't know how can I read, show and edit part of .json file.
Any ideas?
var filesystem = require('fs');
Then refer to the Node documentation here: NodeJS FS
You'll want to load the json file into an object, and then save changes to the file periodically or manually, rather than constantly loading and saving the file.
You can use the jsonfile package to read and write the object.
Read JSON file to object:
var jsonfile = require('jsonfile');
var file = '/path/to/file.json';
jsonfile.readFile(file, function(err, someData) {
if (err) {
// don't use someData
// it's not populated
return;
}
// do something with someData
// there was no error
console.log(someData);
});
Write object to JSON file:
var jsonfile = require('jsonfile');
var file = '/path/to/file.json';
var data = { name: 'John Doe', age: 50, eyes: 'brown', hair: 'black' };
jsonfile.writeFile(file, data, function (err) {
// an error occurred
console.error(err);
});
Best practice is to validate complex data using JSON-schema validation. There are countless JSON editor tools available on GitHub such as JSON Editor Online and Treema. These have been implemented in JavaScript and jQuery and shouldn't prove difficult to follow.

Categories