Skip to content
Advertisement

Write javascript array elements to file

I am trying to have a node js script write some coordinates to a csv file for use in a Newman CLI script. I have the following:

const axios = require('axios');
var move_decimal = require('move-decimal-point');
var sLat = 45.029830;
var sLon = -93.400891;
var eLat = 45.069523;
var eLon = -94.286001;
var arrLatLon = []

axios.get('http://router.project-osrm.org/route/v1/driving/' + sLon + ',' + sLat + ';' + eLon + ',' + eLat + '?steps=true')
.then(function (response) {
    for (let i = 0; i < response.data.routes[0].legs.length; i++) {
        //console.log(response.data)
        for (let ii = 0; ii < response.data.routes[0].legs[i].steps.length; ii++) {
            //console.log('leg ' + i + " - step " + ii + ": " + response.data.routes[0].legs[i].steps[ii].maneuver.location[1] + "," + response.data.routes[0].legs[i].steps[ii].maneuver.location[0]);

            // Declaring Latitude as 'n' & Longitude as 'nn' for decimal calculations
            var n = response.data.routes[0].legs[i].steps[ii].maneuver.location[1]
            var nn = response.data.routes[0].legs[i].steps[ii].maneuver.location[0]

            // Latitude calculatiuons to make 'lat' values API friendly
            var y = move_decimal(n, 6)
            var p = Math.trunc(y);

            // Longitude calculations to make 'lon' values API friendly
            var yy = move_decimal(nn, 6)
            var pp = Math.trunc(yy);

            arrLatLon.push(p +  "," + pp);
        }
        console.log(arrLatLon)
    }
})

I have been looking through and trying numerous different tutorials/code snippets regarding writing the array elements from arrLatLon to an output file on my local machine, but none have been successful. The current code outputs the lat,lon correctly, console.log(arrLatLon) outputs:

[ '45029830,-93400894',
  '44982812,-93400740',
  '44977444,-93400530',
  '44973116,-93410884',
  '44971101,-93450400',
  '45035514,-93766885',
  '45035610,-93766886',
  '45081631,-94286752',
  '45070849,-94282026' ]

any help would be greatly appreciated. Thanks.

Advertisement

Answer

With nodejs you can easily write files using the fs module

const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

in your case you can simply do something like

const fs = require('fs');
// I'm converting your array in a string on which every value is
// separated by a new line character
const output = arrLatLon.join("n");

// write the output at /tmp/test
fs.writeFile("/tmp/test", output, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

Let me forward you to this question for more information Writing files in Node.js

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement