I can't read Excel with Angular2 - excel

I want send Excel with Angular to my Server (SpringBoot). I can't do this.
Error 500 in server
So, I thought that my problem maybe is "Angular doesn't read Excel." I am trying read my Excel with Angular and I get error ->
My intention is "If Angular can read the Excel, then I will try send Excel."
Because I am trying send Excel and I can't send...
Then:
In this code:
fileChange(event) {
let file: File = event.files[0];
let myReader: FileReader = new FileReader();
let fileType = event.parentElement.id;
myReader.onloadend = function (e) {
console.log(myReader.result);
}
console.log('fileType' , fileType);
myReader.readAsText(file);
}
ERROR
ERROR TypeError: Cannot read property '0' of undefined
This code I got the ->
Upload a File and Read Data with FileReader in Angular 2
Before I try with this code:
fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
this.formData.append('uploadFile', file, file.name);
console.log('al cambiar file' , file);
}
console.log(' formdata' , this.formData );
console.log(' fileList' , fileList);
console.log('stack' , event.files[0]);
}
result
With this code I get name the File and last modification but I can't get cells of Excel.

use 'xlsx' package.
npm install xlsx

Related

Read a Excel file with exceljs syncrronuously

I'm trying to read a excel file into a csv-like looking array [ArrayLine1,ArrayLine2,..] with exceljs in nodejs. Exceljs has probably no solution to read a file synchronuously, so I have to build a solution around that. Because of my program in electron with frontend progess display etc. must it run synchronuously. But all my attempts with async functions around the exceljs code doesn't work with the synchronuous frontend.
const workbook = new Excel.Workbook()
var raw = []
var line
workbook.xlsx.readFile(filename).then(() => {
workbook.eachSheet((sheet, sid) => {
sheet.eachRow((row, rid) => {
line = []
row.eachCell((cell, cid) => {
line.push(cell.value)
})
raw.push(line)
})
})
})
//use raw / write the raw to another file
console.log(raw) //echo's: []

Getting error while reading json file using node.js

I am getting the following error while reading the json file using Node.js. I am explaining my code below.
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
My json file is given below.
test.json:
#PATH:/test/
#DEVICES:div1
#TYPE:p1
{
name:'Raj',
address: {
city:'bbsr'
}
}
This json file has some # included strings . Here I need to remove those # included string from this file. I am explaining my code below.
fs.readdirSync(`${process.env['root_dir']}/uploads/${fileNameSplit[0]}`).forEach(f => {
console.log('files', f);
let rawdata = fs.readFileSync(`${process.env['root_dir']}/uploads/${fileNameSplit[0]}/${f}`);
let parseData = JSON.parse(rawdata);
console.log(parseData);
});
Here I am trying to read the code first but getting the above error. My need is to remove those # included lines from the json file and then read all the data and convert the removed lines to object like const obj ={PATH:'/test/',DEVICES:'div1',TYPE:p1}. Here I am using node.js fs module to achive this.
As you said, you need to remove those # lines from the JSON file. You need to code this yourself. To help with that, read the file into a string and not a Buffer by providing a charset to readFileSync.
const text = fs.readFileSync(path, 'utf8');
console.log(text);
const arr = raw.split("\n");
const noComments = arr.filter(x => x[0] !== "#"));
const filtered = noComments.join("\n");
const data = JSON.parse(filtered);
console.log(data);

Reading file using Node.js "Invalid Encoding" Error

I am creating an application with Node.js and I am trying to read a file called "datalog.txt." I use the "append" function to write to the file:
//Appends buffer data to a given file
function append(filename, buffer) {
let fd = fs.openSync(filename, 'a+');
fs.writeSync(fd, str2ab(buffer));
fs.closeSync(fd);
}
//Converts string to buffer
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
append("datalog.txt","12345");
This seems to work great. However, now I want to use fs.readFileSync to read from the file. I tried using this:
const data = fs.readFileSync('datalog.txt', 'utf16le');
I changed the encoding parameter to all of the encoding types listed in the Node documentation, but all of them resulted in this error:
TypeError: Argument at index 2 is invalid: Invalid encoding
All I want to be able to do is be able to read the data from "datalog.txt." Any help would be greatly appreciated!
NOTE: Once I can read the data of the file, I want to be able to get a list of all the lines of the file.
Encoding and type are an object:
const data = fs.readFileSync('datalog.txt', {encoding:'utf16le'});
Okay, after a few hours of troubleshooting a looking at the docs I figured out a way to do this.
try {
// get metadata on the file (we need the file size)
let fileData = fs.statSync("datalog.txt");
// create ArrayBuffer to hold the file contents
let dataBuffer = new ArrayBuffer(fileData["size"]);
// read the contents of the file into the ArrayBuffer
fs.readSync(fs.openSync("datalog.txt", 'r'), dataBuffer, 0, fileData["size"], 0);
// convert the ArrayBuffer into a string
let data = String.fromCharCode.apply(null, new Uint16Array(dataBuffer));
// split the contents into lines
let dataLines = data.split(/\r?\n/);
// print out each line
dataLines.forEach((line) => {
console.log(line);
});
} catch (err) {
console.error(err);
}
Hope it helps someone else with the same problem!
This works for me:
index.js
const fs = require('fs');
// Write
fs.writeFileSync('./customfile.txt', 'Content_For_Writing');
// Read
const file_content = fs.readFileSync('./customfile.txt', {encoding:'utf8'}).toString();
console.log(file_content);
node index.js
Output:
Content_For_Writing
Process finished with exit code 0

Error: ENOENT: no such file or directory, open fs.createWriteStream

I am using node js function fs.createWriteStream in azure instance to download ZIP file from third party but it's giving me error "Error: ENOENT: no such file or directory, open 'D:\home\site\wwwroot\data\499037.zip'"
Below is my code sample.
let filePath = '%HOME%\data\'+pathName+'.zip';
let file = fs.createWriteStream(filePath);
file.on('open', async function(fd) {
//Here is code to process file
}).on('error', function(err) {
context.log('File store error ==> '+err);
file.end();
});
Please suggest what is the exact issue.
Thanks
try add backslash before %HOME% -> \%HOME%.
It may help you split wwwroot folder to www\root.
Also pay attention that in your js backslash seems to wrongly escape quote
let filePath = '%HOME%\data\'+pathName+'.zip';
// ^
// should be
let filePath = '\%HOME%\data\\'+pathName+'.zip';

How to convert a PDF file with NodeJS + Unoconv

I need to convert a docx file to pdf but I don't know very well nodejs, however, I know that the following can be done:
There is a project called unoconv-worker and in it, there is a part where the following line appears:
var child = spawn ('unoconv', [
'--stdout',
'--no-launch',
'--format', job.outputExtension,
job.tempPath
]);
https://github.com/koumoul-dev/unoconv-worker/blob/master/route.js
In my terminal I can convert it in the following way and it works perfectly:
unoconv -f pdf --output="something.pdf" docxtoconvert.docx
However, I would like to give you a file that I gave you the route, so I tried it this way:
var filePath = "/tmp/docxtoconvert.docx";
var child = spawn ("unoconv", [
"-f",
"pdf",
"--output",
"/tmp/something.pdf",
filePath
]);
Output:
Unoconv converter received message on stderr function () {
if (arguments.length === 0) {
var result = this.utf8Slice(0, this.length);
} else {
var result = slowToString.apply(this, arguments);
}
if (result === undefined)
throw new Error('toString failed');
return result;
}
But it has not worked. Could you help me? Thank you
Lot of wrapper modules exists for unoconv that can solve your problem.
You can try this
https://www.npmjs.com/package/unoconv

Resources