Import txt to csv with JavaScript


Im having a problem with a given task.
The task is to write a JavaScript code that would transfer data from a txt file looking like this:
into a CSV file with β€œ0” added before the number so all have total of 8 digits. I was planing to do it with padStart() method but besides that im pretty much clueless :frowning:

How am I supposed to import local txt file into JS while doing operations on the txt and save it as csv?

as for now my code looks something like this:

//-------grab a file -------
const input = document.querySelector(β€˜input[type=β€œfile”]’)
input.addEventListener(β€˜change’, function (e) {
return input.files},false)
//--------save as CSV--------
function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;

    data = || null;
    if (data == null || !data.length) {
        return null;

    columnDelimiter = args.columnDelimiter || ',';
    lineDelimiter = args.lineDelimiter || '\n';

    keys = Object.keys(data[0]);

    result = '';
    result += keys.join(columnDelimiter);
    result += lineDelimiter;

    data.forEach(function(item) {
        ctr = 0;
        keys.forEach(function(key) {
            if (ctr > 0) result += columnDelimiter;

            result += item[key];
        result += lineDelimiter;

    return result;
    function downloadCSV(args) {  
    var data, filename, link;
    var csv = convertArrayOfObjectsToCSV({
        data: input
    if (csv == null) return;

    filename = args.filename || 'export.csv';

    if (!csv.match(/^data:text\/csv/i)) {
        csv = 'data:text/csv;charset=utf-8,' + csv;
    data = encodeURI(csv);

    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);;

However the first part of the code where is const input doesnt seem to work as intendeed. The 2nd part which is supposed to save given txt worked well when the data (data: input) was given with a var like var input = [β€œ1”,β€œ2”,β€œ3”].

Hey @Qbaqba1- welcome to the forums! Quite the fun question :stuck_out_tongue:

For the text file, can it be something you can browse to via the app? Or does the path have to be programmatically specified in the code?

It doesnt have to be spedified in the code as long as it gets job done :slight_smile:

Perfect! This article should help you with loading the file and reading it:

For saving the file, you can provide it as a download. This example should help: