我正在做一些关于使用csvtojson 节点模块将 csv 文件读取为 json 格式的非常简单的测试,我使用下面的代码作为模板
a,b,c
1,2,3
4,5,6
*/
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
console.log(jsonObj);
/**
* [
* {a:"1", b:"2", c:"3"},
* {a:"4", b:"5". c:"6"}
* ]
*/
})
// Async / await usage
const jsonArray=await csv().fromFile(csvFilePath);
我主要关注
// 异步/等待用法
const jsonArray=await csv().fromFile(csvFilePath);
代码段。没错,这是我的代码
// const JSONtoCSV = require("json2csv")
// const FileSystem = require("fs")
async function test()
{
const data = await CSVtoJSON().fromFile('./input.csv')
return data
}
let temp = await test()
console.log(temp)
无论我尝试过哪种方式,我总是收到以下错误
let temp = await test()
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
或者
const data = await CSVtoJSON().fromFile('./input.csv');
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
如果我像这样将代码切换为所有顶级
const CSVtoJSON = require("csvtojson")
// const JSONtoCSV = require("json2csv")
// const FileSystem = require("fs")
const data = await CSVtoJSON().fromFile('./input.csv')
console.log(data)
我不明白为什么这不起作用。
编辑:我按照@tasobu 的说明进行了更改。现在我得到的只是一个回报的承诺
const data = (async () => {
return await CSVtoJSON().fromFile('./input.csv')
})
console.log(data)
Debugger attached.
Promise { <pending> }
Waiting for the debugger to disconnect...
一个Promise
回报的东西在未来,所以你需要一种方法来等待它。
// const CSVtoJSON = require("json2csv")
// const FileSystem = require("fs")
let temp = undefined;
async function test()
{
const data = await CSVtoJSON().fromFile('./input.csv')
// do your stuff with data
temp = data;
console.log(temp) // at this point you have something in.
return true
}
test();
console.log(temp) // at this point nothing was there.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句