Uncaught ReferenceError: XLSX is not defined on drop file - javascript

I want to be able to drag and drop an excel file, but for some reason when declaring my workbook var workbook = XLSX.read(data, {type: rABS ? 'binary':'array'}); it says it's not defined.
I think I'm missing something to connect this index.js to server.js which has the var XLSX = require('xlsx'); in it. I've looked and looked online and haven't found the right fix. I would like to avoid using a module to require() inside of HTML.
What I think is the important code:
server.js:
var express = require("express");
var app = express();
var XLSX = require('xlsx');
var fs = require('fs');
var JSON = require('JSON');
var path = require('path');
index.js:
$(document).ready(function(){
var rABS = true; // true: readAsBinaryString ; false: readAsArrayBuffer
$excelHolder.on('drop', function(e){
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
console.log("got to before reader");
reader.onload = function (e) {
console.log("got to reader.onload");
var data =e.target.result;
var workbook = XLSX.read(data, {type: rABS ? 'binary':'array'});
var sheet_name_list = workbook.SheetNames;
var excelObj = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
var json = JSON.stringify(excelObj);
var callback = "looks like it worked";
console.log("did it upload?");
fs.writeFile('excelfile.json', json, function(err){
(err) ? console.error(err) : console.log(callback.toString());
});
// preview?
};
if(rABS) reader.readAsBinaryString(file); else reader.readAsArrayBuffer(file);
});
}
index.html:
<div class="huge">22</div>
<div>Uploads!</div>
<input name="uploads[]" type="file" accept=".xls,.xlsx,.ods,.csv" style="display: none;" id="excelInput">
Any help is much appreciated.

I can see a few problems here:
fs and path are modules that are built into NodeJs, hence they are not available in the browser.
You'll need some kind of build tool for your JS if you want to use require for client-side code. Browserify and Webpack are good places to start.
If you don't want to get into that (It's complex so I wouldn't blame you!) you can add the XLSX module to the browser with a <script> tag: https://www.npmjs.com/package/xlsx#installation - it seems like it should work.
There are some examples on the XLSX GitHub page, one of which includes drag & drop and may help you get where you want? https://github.com/SheetJS/js-xlsx (And specifically https://github.com/SheetJS/js-xlsx/tree/master/demos/datagrid)

if you forget to add the library cdn or install it, he will generate this error
add this script or any new:
<script type="text/javascript" src="https://unpkg.com/xlsx#0.15.1/dist/xlsx.full.min.js"></script>

Related

Trying to read and print local file to console

I'm new to JS and I'm trying to just print the "loadavg" file to the console when I run my program. I don't want to bother doing it through the browser just yet.
This is what I've come up with
function readTextFile() {
var contents = new File();
contents.readTextFile("file:///proc/loadavg");
console.log(contents);
}
I get no errors but the code still will not work
With Node JS.
Create a folder and enter it:
mkdir filereader
cd filereader
Init Node JS:
npm init
Edit index.js as new file in the directory:
var fs = require('fs');
let filename = '/proc/loadavg';
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log(data)
});
Save, exit the file, and run the script:
node index.js
Image here in the link:
running the script on Ubuntu Terminal
If you dont want to use nodeJS the only way to read text file using javascript is to use file Input
HTML:
<input type="file" id="file_input">
JS:
const fileInput = document.getElementById("file_input")
fileInput.addEventListener("input", (event) => {
const file = e.target.files[0]
if(file){
const reader = new FileReader()
reader.readAsText(file)
reader.onload = () => console.log(reader.result)
}
})
You can use nodejs streams to achieve this.
const fs = require('fs'),
var reader = fs.createReadStream('./proc/loadavg');
stream.on('data', function(chunk) {
process.stdout.write(chunk);
});

Editing an XML document

I am new to JavaScript and need the ability to create, edit and export an XML document on the server side. I have seen different options on the Internet, but they do not suit me.
It seems that I found one suitable option with processing my XML file into JSON, and then back and then export it through another plugin, but maybe there is some way to make it easier?
Thanks!
I recently came across a similar problem. The solution turned out to be very simple. It is to use XML-Writer
In your project folder, first install it via the console
npm install xml-writer
Next, first import it and create a new file to parse what's going on here:
var XMLWriter = require ('xml-writer');
xw = new XMLWriter;
xw.startDocument ();
xw.startElement ('root');
xw.writeAttribute ('foo', 'value');
xw.text ('Some content');
xw.endDocument ();
console.log (xw.toString ());
You can find more information here and at the bottom of the page see the different code for each item. In this way, you can create, edit and export xml files. Good luck and if something is not clear, write!
Additional
You will need also fs module
const fs = require("fs")
const xmlParser = require("xml2json")
const formatXml = require("xml-formatter")
Completed code:
const fs = require("fs")
const xmlParser = require("xml2json")
const formatXml = require("xml-formatter")
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.startElement('man');
xw.writeElement('name', 'Sergio');
xw.writeElement('adult', 'no');
xw.endElement();
xw.startElement('item');
xw.writeElement('name', 'phone');
xw.writeElement('price', '305.77');
xw.endElement();
xw.endDocument();
const stringifiedXmlObj = JSON.stringify(xmlObj)
const finalXml = xmlParser.toXml(stringifiedXmlObj)
fs.writeFile("./datax.xml", formatXml(finalXml, { collapseContent: true }), function (err, result) {
if (err) {
console.log("Error")
} else {
console.log("Xml file successfully updated.")
}
})
})

node.js How to use a url as pdf-path to work with pdf2json

I'm using node.js and pdf2json parser to parse a pdf file.
Currently it is working with a local pdf file.
But I'm trying to get a pdf-file through the URL/HTTP Module of node.js and I want to open this file to parse it.
Is there any possibility to parse/work with an online pdf?
let query = url.parse(req.url, true).query;
let pdfLink = query.pdf;
...
pdfParser.loadPDF(pdfLink + "");
So the url should be given through the url like: https://localhost:8080/?pdf=http://whale-cms.de/pdf.pdf
Is there any way to parse it within the online pdf/link?
Thanks in advance.
Im just faced with the same problem, and found a solution:
var request = require('request');
var PDFParser = require("pdf2json");
var pdfUrl = "http://localhost:3000/cdn/storage/PDFFiles/sk87bAfiXxPre428b/original/sk87bAfiXxPre428b"
var pdfParser = new PDFParser();
var pdfPipe = request({url: pdfUrl, encoding:null}).pipe(pdfParser);
pdfPipe.on("pdfParser_dataError", err => console.error(err) );
pdfPipe.on("pdfParser_dataReady", pdf => {
let usedFieldsInTheDocument = pdfParser.getAllFieldsTypes();
console.log(usedFieldsInTheDocument)
});
Source from:
https://github.com/modesty/pdf2json/issues/65
Cheers

how to set name of file being uploaded in connect-multiparty?

I have have one page where I want to accept one file and 3-4 user inputs , I was able to achieve this using connect-multiparty middle-ware but the name of uploaded file is something gibberish with correct extension and uploaded files contents are too correct.
I want to achieve below things
Set name of file being uploaded
Create copy of file with different name if the file with same name exists in target directory
Set max limit on size and restrict type of file.
I searched on net but could not find any working example. My complete code is as below
var express = require('express');
var router = express.Router();
var fs = require('fs');
var multiparty = require('connect-multiparty');
var multipartyMiddleware = multiparty({
uploadDir : '../public/uploads'
});
router.post('/api/user/uploads', multipartyMiddleware, function(req, res) {
var file = req.files.file;
console.log(file.name);
console.log(file.type);
console.log(file);
console.log(req.body.test);
console.log("The file was saved!");
res.json({
success : 1
});
return;
});
module.exports = router;
You will have to rename the file after being copied using fs.rename(), or modify the source code of multiparty inside node_modules. Inside their code they have a function that does the renaming:
function uploadPath(baseDir, filename) {
var ext = path.extname(filename).replace(FILE_EXT_RE, '$1');
var name = randoString(18) + ext;
return path.join(baseDir, name);
}
I have done some modifications to their code so I could use it a little bit like multer:
https://gist.github.com/Edudjr/999c80df952458cc583272a5161b4d08
You would use it like so:
var EXT_RE = /(\.[_\-a-zA-Z0-9]{0,16}).*/g;
var options = {
uploadDir : path.join(__dirname,'../public/images'),
filename: function(filename, callback){
var name = filename.replace(EXT_RE, "");
callback(name+'-YEAH.png');
}
}
var form = new multiparty.Form(options);
They strongly advise you to save the files in the temp folder to prevent DoS on your server.
https://github.com/pillarjs/multiparty/issues/64
You can access it easily, I used this to get file name.
console.log(req.files.uploads.path.split('\\')[1]);
I am using uploads from Angular.

Node Js : Unable to find error in below file filter code

I have written small code to get files filtered by extension. And my point of view logic is fine but I am unable to point out why I am not getting expected output.
Please have a look.
CODE
var fs = require('fs')
var path = require('path')
path_name = process.argv[2]
ext_name = "."+process.argv[3]
var filter_function = function ( path_name,exthide_name,callback) {
fs.readdir(dirpath,function(err,list) {
if(err) return console.error(err)
for ( var i in list) {
if(path.extname(list[i]) == ext_name)
console.log(list[i])
}
})
}
module.exports=filter_function
Output :
linuxmen#linuxmen-fresh:~/test/test1$ node ownModuleNode.js /home/linuxmen/test/test1/ js
linuxmen#linuxmen-fresh:~/test/test1$
But I have so many files with js extension in that directory.
Proof:
linuxmen#linuxmen-fresh:~/test/test1$ ls *js
check_mod1.js ex1.js ex2.js ex3.js ex4.js ex5.js ex6.js ex7.js ex8.js filter.js filter_use.js modse.js ownModuleNode.js se.js use_mod1.js using_module.js
Could please help , what I am missing.
Update - 1 : I am using above code a module file and calling it here.
File using above code
var mymodule = require('./ownModuleNode')
mymodule.filter_function(process.argv[2],process.argv[3])
Update 2 :
var fs = require('fs')
var path = require('path')
path_name = process.argv[2]
ext_name = "."+process.argv[3]
console.log("path_name :",path_name,"extname:",ext_name)
var filter_function = function ( path_name,ext_name,callback) {
fs.readdir(path_name,function(err,list) {
if (err) console.error(err)
console.log(list)
for ( var i in list) {
if(path.extname(list[i]) == ext_name)
console.log(list[i])
}
})
}
module.exports=filter_function
Output:
linuxmen#linuxmen-fresh:~/test/test1$ node ownModuleNode.js /home/linuxmen/test/test1/ js
pathanme : /home/linuxmen/test/test1/ extname: .js
Thank you.
It looks like you are exporting the function directly. When you require() it, you just getting the function. You'll need to use your module in your application. Put this in 'app.js' in the same dir as ownModuleNode.js:
var filterFunction = require('./ownModuleNode');
filterFunction(process.argv[2], process.argv[3]);
Then call it with:
node app ~/Documents/dev/project .js
Outputs:
app.js
ownModuleNode.js
Note that when you pass the extension, you need the preceding dot because path.extname() returns the dot.

Categories