简体   繁体   中英

unexpected token output json file using node.js

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);

It is strange when json.push doesn't work here. When I do console like

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

You're getting an unexpected token error because there's an unexpected token:

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

An object initializer consists of key/value pairs. In ES2015+, if we're getting the value from a variable, we can just include the variable and the key will be inferred from the variable name, but you can't do that with any arbitrary expression.

So for instance, if you want the object's key to be foo :

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

Or if you didn't want an object at all, just the value, remove the {} :

json.push(file.split('.')[0]);

The next problem, once you fix the json.push call, is that no calls to json.push will be made before your writeFile call is made, because readdir calls its callback asynchronously . More: fs.readdir and How do I return the response from an asynchronous call?

change this

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

to

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

and

you are using async code as sync code. in your your file is written way before your readdir is executed.

the correct way to do it is as follows.

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

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

or if you want to so it in sync the do it as follows

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

let json = [];
let files = fs.readdirSync(targetFolder);

files.forEach(file => {
    json.push({'fileName': file.split('.')[0]})
});

jsonfile.writeFile(targetFolder ,json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM