javascript - 将javascript数组元素写入文件
问题描述
我正在尝试让节点 js 脚本将一些坐标写入 csv 文件以在 Newman CLI 脚本中使用。我有以下内容:
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)
}
})
我一直在查看并尝试许多不同的教程/代码片段,这些教程/代码片段涉及将数组元素从arrLatLon
本地计算机上的输出文件写入,但没有一个成功。当前代码正确输出纬度,经度,console.log(arrLatLon)
输出:
[ '45029830,-93400894',
'44982812,-93400740',
'44977444,-93400530',
'44973116,-93410884',
'44971101,-93450400',
'45035514,-93766885',
'45035610,-93766886',
'45081631,-94286752',
'45070849,-94282026' ]
任何帮助将不胜感激。谢谢。
解决方案
使用 nodejs,您可以使用fs
模块轻松编写文件
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
在你的情况下,你可以简单地做类似的事情
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!");
});
让我转发这个问题以获取更多信息在 Node.js 中编写文件
推荐阅读
- azure - 从 Azure 存储帐户下载所有文件
- xcode - Xcode 11 模拟器看起来很奇怪
- ios - 我需要在delegate.m文件中添加代码,我只能在flutter中找到delegate.swift
- java - 我如何在java中使用闭包编译器
- angular - 使用 nginx 作为反向代理在 Azure Service Fabric 中部署 Angular8 应用程序
- python - 告诉脚本等到按钮可点击?
- eclipse - 在 Eclipse 调用时从命令行指定 Eclipse 工作区
- python - 根据先前列中满足的某些条件在数据框中创建新列
- javascript - 无法在阿波罗服务器突变中使用 console.log() 功能
- ruby - 法拉第正在将我的标题从大写更改为大写