我正在尝试编写一些基本代码,以便稍后在更大的聊天机器人中使用。该代码接受用户输入,检查文件是否已存在,如果不存在,则从 api 提取数据并保存文件。
我可以让每个部分独立工作(例如,指出 readfile 保存文件并指出 write 成功读取文件),但是当我尝试将它们一起运行时,我收到 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']);
});
});
}
}
Node 似乎跳过了请求之前的所有代码,因为 console.log("true) 确实返回,但之后没有返回
到目前为止,我已经尝试将它们分成函数(这可能是更好的礼仪),使用 request.get(...).on(...) 将 readFile 更改为 readFileSync
任何帮助将不胜感激
最佳答案
您的代码只需要进行一些小的修改。由于我无权访问您的 API,因此我使用公共(public) 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)
})
});
}
});
}
关于javascript - Node.js 忽略读取尚不存在的文件的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49219841/