【发布时间】:2021-11-04 10:11:50
【问题描述】:
我正在做一些关于使用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);
我主要关注的是
// 异步/等待使用
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...
【问题讨论】:
-
错误信息很清楚:你的代码是模块吗?你的
await在async函数内吗?如果答案是“否”,那就是问题所在。 -
为什么
csvtojson提供的是JS对象,而不是json? -
只能在异步函数中使用 await。您已经在 let temp = await test() 中使用了它
-
正如 Invizi 所说,将
let temp = await test()替换为let temp = test()
标签: javascript node.js asynchronous async-await