0

I want to share variable called pathfinder between two javascript files. I don't know where to initiate my variable : I want to edit it in my upload.js with jQuery (at the beginning) :

$(".sub-menu li").on("click", function() {
    pathfinder = "";
    console.log($(this).text());
    console.log($(this).parent().prev().text());
    pathfinder = $(this).parent().prev().text() + "/" + $(this).text();
    console.log(pathfinder);
});

$('.upload-btn').on('click', function() {
    $('#upload-input').click();
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');
});

$('#upload-input').on('change', function() {

    var files = $(this).get(0).files;

    if (files.length > 0) {
        // create a FormData object which will be sent as the data payload in the
        // AJAX request
        var form = document.getElementById("form")
        var formData = new FormData(form);

        // loop through all the selected files and add them to the formData object
        for (var i = 0; i < files.length; i++) {
            var file = files[i];

            // add the files to formData object for the data payload
            formData.append('uploads[]', file, file.name);
        }

        $.ajax({
            url: '/upload',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data) {
                console.log('upload successful!\n' + data);
            },
            xhr: function() {
                // create an XMLHttpRequest
                var xhr = new XMLHttpRequest();

                // listen to the 'progress' event
                xhr.upload.addEventListener('progress', function(evt) {

                    if (evt.lengthComputable) {
                        // calculate the percentage of upload completed
                        var percentComplete = evt.loaded / evt.total;
                        percentComplete = parseInt(percentComplete * 100);

                        // update the Bootstrap progress bar with the new percentage
                        $('.progress-bar').text(percentComplete + '%');
                        $('.progress-bar').width(percentComplete + '%');

                        // once the upload reaches 100%, set the progress bar text to done
                        if (percentComplete === 100) {
                            $('.progress-bar').html('Done');
                        }

                    }

                }, false);

                return xhr;
            }
        });

    }
});

And once it has been edited, I want to retrieve it in my app.js (in app.post('/upload', function(req, res)) :

var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var util = require('util');
var excel = require('excel4node');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {

    res.sendFile(path.join(__dirname, 'views/index.html'));

});


app.post('/upload', function(req, res) {

            var fields = [];
            // create an incoming form object
            var form = new formidable.IncomingForm();

            // specify that we want to allow the user to upload multiple files in a 
            single request
            form.multiples = true;

            // store all uploads in the /uploads directory
            form.uploadDir = path.join(__dirname, '/uploads/' + pathfinder + "/Données 
                brutes ");

                // every time a file has been uploaded successfully,
                // rename it to it's orignal name
                form.on('file', function(field, file) {
                    fs.rename(file.path, path.join(form.uploadDir, file.name));
                });


                // log any errors that occur
                form.on('error', function(err) {
                    console.log('An error has occured: \n' + err);
                });


                // parse the incoming request containing the form data
                form.parse(req, function(err, fields, files) {
                    res.writeHead(200, {
                        'content-type': 'text/plain'
                    });
                    res.write('received the data:\n\n');
                    res.end(util.inspect({
                        fields: fields,
                        files: files
                    }));

                    // Create a new instance of a Workbook class
                    var workbook = new excel.Workbook();
                    // Add Worksheets to the workbook
                    var worksheet = workbook.addWorksheet('Sheet 1');
                    // Create a reusable style


                    worksheet.cell(1, 1).string('PKD')
                    worksheet.cell(1, 2).string('PKF')
                    var PK = parseInt(fields['PKD']);
                    for (var i = 2; i <= ((fields['PKF'] - fields['PKD']) / 0.2) + 1; i++) {
                        for (var j = 1; j < 3; j++) {

                            worksheet.cell(i, j).number(PK)
                            PK += 0.2;
                        }
                        PK -= 0.2;
                    }

                    workbook.write('uploads/' + pathfinder + '/Données brutes/' + 'pk.xlsx', function(err, stats) {
                        if (err) {
                            console.error(err);
                        }
                        console.log("Fichier PK correctement créé"); // Prints out an instance of a node.js fs.Stats object 
                    });



                });

                // once all the files have been uploaded, send a response to the client
                form.on('end', function() {

                    res.end('success');
                    //var spawn = require("child_process").spawn;
                    //var process = spawn('python',["python_scripts/script.py"]);

                });

            });


        var server = app.listen(3000, function() {
            console.log('Server listening on port 3000');
        });

Where should I initiate it ? I tried in index.html under script tag but it's undefined...

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
Saguaro
  • 233
  • 3
  • 12
  • 1
    Some sensible code indentation would be a good idea. It helps us read the code and more importantly it will help **you debug your code**. [Take a quick look at a coding standard](http://www.php-fig.org/psr/psr-2/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – GrumpyCrouton Aug 07 '17 at 18:37
  • @GrumpyCrouton agreed, although a JS coding style might be better in this case? Anyway, the rules should be similar even though the language is different – lumio Aug 07 '17 at 18:40
  • Add pathfinder to your form so it gets posted alongside the other data, and can be retrieved by the server code in app.post. – James Aug 07 '17 at 18:41
  • @lumio I don't know what that means buddy – GrumpyCrouton Aug 07 '17 at 18:41
  • @GrumpyCrouton your link is PHP specific while he is writing JavaScript so it might be irritating. Some coding styles like https://github.com/airbnb/javascript might have been better - but we are discussing it in the wrong place - sorry about that :D – lumio Aug 07 '17 at 18:43
  • @lumio you're totally right I usually lurk in the PHP tag and that is a copy and paste message :P Sorry about that! (I was confused when you called it a CS, I've never seen it "acronymized") – GrumpyCrouton Aug 07 '17 at 18:45

0 Answers0