我正在做一些关于使用 csvtojson node module 将 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);
我主要关注的是// Async / await usage
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 的说明进行了更改。现在我得到的只是一个返回的 promise
const data = (async () => {
return await CSVtoJSON().fromFile('./input.csv')
})
console.log(data)
Debugger attached.
Promise { <pending> }
Waiting for the debugger to disconnect...
最佳答案
您可以在此处使用 IIFE(了解更多信息 here)
(async function main () {
// You can use await inside this function block
})();
关于javascript - 异步/等待语法错误 : await is only valid in async functions and the top level bodies of modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69089471/