我刚接触过Javascript,也许你能帮我理解这一点。这里的csvtojson示例都显示了登录到控制台的情况,这很好:
https://www.npmjs.com/package/csvtojson#from-csv-file-to-json-array
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
console.log(jsonObj);
})我的问题是-如何在此范围之外使用jsonObj?我只想要一个简单的全局变量,我可以在脚本的后面访问JSON。
发布于 2020-12-29 06:15:39
您可以使用 IIFE (立即调用函数表达式)包装所有异步代码,并将值存储在全局变量中,并且可以在异步生命周期中实现该值。要存储值并从任何需要等待结果的地方访问它,然后访问由于js的异步和单线程性质而产生的值。
const csv = require('csvtojson');
let arr = [];
(async function () {
const json = await csv().fromFile('./demo.csv');
await arr.push(json);
console.log(arr);
})()发布于 2020-12-29 06:01:08
您可以使用“转换-excel-to-json”npm包。一个例子如下:
'use strict';
const excelToJson = require('convert-excel-to-json');
const result = excelToJson({
sourceFile: 'SOME-EXCEL-FILE.xlsx'
});
// result will be an Object containing keys with the same name as the sheets found on the excel file. Each of the keys will have an array of objects where each of them represents a row of the container sheet. e.g. for a excel file that has two sheets ('sheet1', 'sheet2')
{
sheet1: [{
A: 'data of cell A1',
B: 'data of cell B1',
C: 'data of cell C1'
}],
sheet2: [{
A: 'data of cell A1',
B: 'data of cell B1',
C: 'data of cell C1'
}]
}然后,您可以在任何地方使用结果对象。
发布于 2020-12-29 06:01:51
您可以尝试使用async和await,只需编写一些您希望在IIFE中执行的代码,例如:
const csvFilePath = './aCSV.csv';
const csv = require('csvtojson');
// a IIFE
(async () => {
const jsonObj = await csv().fromFile(csvFilePath);
console.log(jsonObj);
// [ { a: '1', b: '2', c: '3' }, { a: '4', b: '5', c: '6' } ]
})();https://stackoverflow.com/questions/65487687
复制相似问题