Read a Excel file with exceljs syncrronuously - node.js

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: []

Related

use .sfz soundfonts to render audio with WebMScore

I'm using WebMScore to render audio of music scores (it's a fork of MuseScore that runs in the browser or node).
I can successfully load my own, local .sf2 or .sf3 files, however
Trying to load an .sfz soundfont throws error 15424120. (And error.message is simply 'undefined'.)
Unlike .sf2 and .sf3, which contain the sounds and instructions in a single file, the .sfz format is just a text instruction file that refers to a separate folder of samples.
The reason I need the .sfz is that I need to be able to edit the .sfz file textually and programatically without an intervening Soundfont generator.
Is there a way to use .sfz's? Do I need to specify Zerberus (the Musescore .sfz player)? Do I need a different file structure? Please see below.
My environment is node js, with the following test case and file structure:
File Structure
Project Folder
app.js
testScore.mscz
mySFZ.sfz
samples
one.wav
two.wav
etc.wav
Test Case (Works with .sf3 , errors with .sfz)
const WebMscore = require('webmscore');
const fs = require('fs');
// free example scores available at https://musescore.com/openscore/scores
const name = 'testScore.mscz';
const exportedPrefix = 'exported';
const filedata = fs.readFileSync(`./${name}`);
WebMscore.ready.then(async () => {
const score = await WebMscore.load('mscz', filedata, [], false);
await score.setSoundFont(fs.readFileSync('./mySFZ.sfz'));
try { fs.writeFileSync(`./${exportedPrefix}.mp3`, await score.saveAudio('mp3')); }
catch (err) { console.log(err) }
score.destroy();
});

Adding files in directory to an array

I am really new to node.js. I need to read .json files from a directory and then add them to an array and return it. I am able to read each file separately by passing the address:
const fs = require("fs");
fs.readFile("./fashion/customer.json", "utf8", (err, jsonString) => {
if (err) {
console.log("Error reading file from disk:", err);
return;
}
try {
const customer = JSON.parse(jsonString);
console.log("Customer address is:", customer.address); // => "Customer address is: Infinity Loop Drive"
} catch (err) {
console.log("Error parsing JSON string:", err);
}
});
But the same fashion folder has multiple json files. I want to add these files to an array and then return it. I tried using readdirSync but that just returned the file names. Is it possible to add json files to an array and return it?
Basically I require an array of this format:
Array[{contents of json file1}, {contents of json file2}, .....]
Any help is appreciated!
Here is a simple solution to your question:
const fs = require("fs");
const jsonFolder = './fashion'
var customerDataArray = []
fs.readdirSync(jsonFolder).forEach(file => {
let fileData = JSON.parse(fs.readFileSync(jsonFolder+'/'+file))
customerDataArray.push(fileData)
});
console.log(customerDataArray)
readdirSync returns an array with all the file names or objects in the directory. You can use forEach to iterate through every item in the array, which will be the file names in this scenario. To read the contents of each file, use readFileSync and specify the path to the file as the name of the directory plus the name of the file. The data is returned as a buffer and needs to be parsed using JSON.parse(), and then it is pushed to the customerDataArray.
I hope this answers your question!

Testcafe - How to call a excel data driven class from main class in testcafe?

Getting "cannot read "forEach' undefined. I have implemented as you said. but still, I am getting errors. Pls give a solution for this
//data-driven script in a separate class
import xlsx from "node-xlsx"
// read logic of excel
export function readDataFromExcelFile(filePath) {
const excelFile = xlsx.parse(filePath)
const excelSheet = excelFile.find((sheets) => sheets.name ==
"sheetname")
const excelSheetData = excelSheet.data
const headers = excelSheetData.shift()
const dataSet = excelSheetData.map((row) => {
const user = {}
row.forEach((data, idx) => (user[headers[idx]] = data))
return user
})
}
If I get it right, you're basically trying to implement data-driven tests with TestCafé. In your case, the data source seem to be Excel files. Assuming that you have the code to read from excel files in one JavaScript file:
// This is your file that contains your excel reading code, such as excel.js
import xlsx from "node-xlsx"
// the export keyword is necessary for the function so that it can be imported within other files
export function readDataFromExcelFile(filePath) {
// your excel file reading code goes here
}
Add the following code to your JavaScript file containing the test code to iterate over your dataSet that you previously retrieved from your Excel files and make whatever actions and assertions you need to do, based on your data:
import { readDataFromExcelFile} from './excel.js'; // import excel reading function from excel.js
// Create a fixture (test-suite) for your your data-driven tests
fixture `My data-driven tests`
.page `https://www.mySampleUrl/further/stuff/`;
const dataSet = readDataFromExcelFile("path/to/your/excel.xlsx")
// iterate over the dataSet that was previously returned from your readDataFromExcelFile function
dataSet.forEach(data => {
// Create & execute a test for each dataSet entry
test(`Test for'${data.someTestIdentifier}'`, async t => {
// Your test specific content. Test actions and assertions/validations come here
await t.expect(Selector("h1").textContent).eql(data.someDataEntry);
});
});
Take a further look into data-driven Tests with TestCafé here.

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);

ExcelJS - TypeError: s.createWriteStream is not a function

So I am using Electron with React to create an application, where I want to do some basics Excel operations. Here is my code
import Excel from 'exceljs';
var sheetName = 'Inventory';
var fileName = '../../inventory.xlsx';
var workbook = new Excel.Workbook();
export const createWorkbook = () => {
workbook.addWorksheet(sheetName);
workbook.xlsx.writeFile(fileName).then(() => {
console.log('Excel file created');
}).catch((error) => {
console.log(`${error}`);
});
}
I didn't include the columns and rows function and read as the problem is occurring in this createWorkbook function. This is the code I used in the react component
<button onClick={createWorkbook}>Create an Excel File</button>
I made sure to import it properly and ensure it's working. It's entering into the function, but this is the error I get and it's from the writeFile function I believe.
TypeError: s.createWriteStream is not a function

Resources