简体   繁体   English

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

[英]Node.js ignoring code to read a file that does not yet exist

I am trying to write some basic code for use in a larger chatbot later. 我正在尝试编写一些基本代码,以便稍后在更大的聊天机器人中使用。 The code takes a user input, checks to see if a file already exists and if it does not, pull data from an api and save the file. 该代码接受用户输入,检查文件是否已经存在,如果不存在,请从api中提取数据并保存文件。

I can get each part working independently (for example, noting out the readfile saves the file and noting out the write successfully reads the file) however when I try to run them together I get an ENOENT error. 我可以使每个部分独立工作(例如,记下readfile会保存文件,而记下write会成功读取文件),但是当我尝试同时运行它们时,会出现ENOENT错误。 The entire code can be seen below. 整个代码可以在下面看到。

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']);
      });
    });
  }
}

It seems like node skips all the code just before the request since the console.log("true) does return but nothing afterwards 由于console.log(“ true)确实返回,但是之后什么也没有,因此节点似乎在请求之前跳过了所有代码。

So far I have tried separating them into functions (which might be a better etiquette), changing the readFile to readFileSync, using request.get(...).on(...) 到目前为止,我已经尝试将它们分成功能(可能是更好的礼节),使用request.get(...)。on(...)将readFile更改为readFileSync。

Any help will be greatly appreciated 任何帮助将不胜感激

Your code just need a few minnor corrections. 您的代码只需要进行一些轻微的更正。 Since I don't have access to your API, I'm using a public one (last.fm/api) but it works with JSON almost the same way you want. 由于我无权访问您的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)
                })
            });
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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