javascript - 使用node.js意外的 token 输出json文件

标签 javascript json node.js ecmascript-6

const targetFolder = './app/images/';
const fs = require('fs');
const jsonfile = require('jsonfile');

let json = [];
fs.readdir(targetFolder , (err, files) => {
  files.forEach(file => {
    json.push({file.split('.')[0]})
  });
})

jsonfile.writeFile(targetFolder , json);

当 json.push 在这里不起作用时,这很奇怪。当我像控制台一样

console.log(file.split('.')[0]) I can see the list of files in my terminal.

最佳答案

您收到意外 token 错误,因为存在意外 token :

json.push({file.split('.')[0]})
// Here -------^

对象初始值设定项由键/值对组成。在 ES2015+ 中,如果我们从变量获取值,我们可以只包含该变量,并且将从变量名称推断出键,但不能使用任何任意表达式来做到这一点。

例如,如果您希望对象的键为 foo:

json.push({foo: file.split('.')[0]});

或者,如果您根本不需要对象,只需要值,请删除 {}:

json.push(file.split('.')[0]);
<小时/>

修复 json.push 调用后,下一个问题是,在调用 writeFile 之前不会调用 json.push,因为 readdir异步调用其回调。更多:fs.readdirHow do I return the response from an asynchronous call?

关于javascript - 使用node.js意外的 token 输出json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975329/

相关文章:

node.js - “myTable”未与模型关联

javascript - Python-解析请求响应

javascript - 如何使用nodejs/js通过id找到json对象

javascript - 当存在 ng-switch-when 时,Angularjs v1 Kendo UI DOM 元素通过 $scope 进行访问

javascript - 纯 JavaScript 图像抓取缩放?

json - Elasticsearch 7.8.1:批量添加json错误无法读取数据

node.js - 如何在 Gulp-Jade 中设置默认文档类型

node.js - 创建 OAuth API 时的应用程序 token / secret

javascript - setTimeout 在事件监听器中不起作用

javascript - 在 C# 中以编程方式设置和获取浏览器窗口坐标值 (x,y)