Node.js忽略代码来读取尚不存在的文件

时间:2018-03-11 12:10:43

标签: javascript node.js

我正在尝试编写一些基本代码,以便稍后在更大的聊天机器人中使用。代码接受用户输入,检查文件是否已存在,如果不存在,则从api中提取数据并保存文件。

我可以让每个部分独立工作(例如,注意读取文件保存文件并注意写入成功读取文件)但是当我尝试一起运行它时,我得到一个ENOENT错误。整个代码可以在下面看到。

const path = require('path');
const readline = require('readline-sync');
const fs = require('fs');
const request = require('request');

//put api url into variable
const api = "http://vocadb.net/api/";

var command = readline.question("enter a command: ");
//only run with commands that start with !
if (command.startsWith('!')) {
  if (command.startsWith('!artist')) {

    //split input, strip command char and use as file name
    userCommand = command.replace('!', '');
    userCommand = userCommand.split(' ');
    var filename = userCommand[0] + userCommand[1] + ".txt";
    var file = path.basename(filename);

    //if file does not exist, fetch JSON from api and save to file
    if (!fs.existsSync(file)) {
      console.log("true");
      request(api + "artists?query=" + userCommand[1] + "&artistType=producer&lang=English", function(error, response, body) {
        if(err) throw err;
        console.log(body);
        var artist = JSON.parse(body);
        console.log(artist);
        //if json has no items do not create file, print incorrect and stop execuution
        if (artist['items'] == '') {
          console.log("Artist could not be found");
          throw err;
        } else {
          fs.writeFile(file, JSON.stringify(artist), (err) => {
            if (err) throw err;
            console.log('file saved');
          });
        }
      });
    }

    fs.readFile(file, 'utf8', (err, data) => {
      if (err) throw err;
      artist = JSON.parse(data);
      request(api + "songs?artistId=" + artist['items'][0]['id'] + "&maxResults=2&getTotalCount=false&sort=RatingScore&lang=English", function(error, response, body) {
        var songs = JSON.parse(body);
        console.log(artist['items'][0]['name'] + "\n" + artist['items'][0]['defaultName'] + "\n");
        console.log("Top songs:\n" + songs['items'][0]['name'] + "\n" + songs['items'][0]['defaultName'] + "\n" + songs['items'][0]['artistString'] + "\n");
        console.log(songs['items'][1]['name'] + "\n" + songs['items'][1]['defaultName'] + "\n" + songs['items'][1]['artistString']);
      });
    });
  }
}

似乎节点在请求之前跳过所有代码,因为console.log(" true)确实返回但之后没有任何内容

到目前为止,我已经尝试将它们分成函数(这可能是一个更好的礼仪),使用request.get(...)更改readFile到readFileSync。(...)

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您的代码只需要进行一些修正。由于我无法访问您的API,因此我使用的是公共API(last.fm/api),但它与JSON的工作方式几乎相同。

var fs = require('fs');
var request = require('request');
var api = 'http://ws.audioscrobbler.com/2.0/?callback=&method=';

var file = "test.txt";
var userCommand = 'amy';

if (!fs.existsSync(file)) {
    console.log("file not found");
    request(api + "artist.getinfo&artist=" + userCommand + '&api_key=57ee3318536b23ee81d6b27e36997cde&format=json&_=1520772613660', function(err, response, body) {
        if (err) throw err;
        else {
            var data = JSON.parse(body);
            if (!data.artist) {
                console.error("Artist could not be found");
                throw err;
            } else {
                fs.writeFile(file, JSON.stringify(data), function (err) {
                    if (err) throw err;
                    else console.log('file saved');
                });
            }
        }
    });
} else {
    console.log('found file "' + file + '"');
    fs.readFile(file, 'utf8', function (err,data) {
        if (err) throw err;
        else {
            artist = JSON.parse(data);
            request(api + "artist.getTopTracks&artist=" + userCommand + "&api_key=57ee3318536b23ee81d6b27e36997cde&format=json&_=1520772613660", function(error, response, body) {
                var data = JSON.parse(body);
                //console.log(data)
                var songs = data.toptracks.track;
                songs.forEach(function (song) {
                    console.log(song.name)
                })
            });
        }
    });
}