简体   繁体   English

NodeJs:fs.appendFile函数似乎错过了给定的最后一个字符串

[英]NodeJs: fs.appendFile function seems to miss last String given

I'm new to nodejs I was trying the append function. 我是NodeJS的新手,我尝试了append函数。 When I run below code that simply takes User input after prompting him, about fav singer and puts in a file with singer name. 当我在下面的代码中运行时,仅在提示用户之后输入用户输入,然后将其添加到收藏夹中,并放入带有歌手名称的文件。 And appending fav songs, It seems if user entered exit it should be append it to the file but, its not??? 并附加收藏歌曲,似乎如果用户输入退出应将其附加到文件,但不是??? Meanwhile if its change to appendFileSync (Synchronous version of the fn) exit is added?? 同时,如果添加了对appendFileSync(fn的同步版本)的更改,则退出?

Code: 码:

var readline = require ('readline');
var fs = require('fs');
var rl = readline.createInterface(process.stdin, process.stdout);
var singer = {
  name:'',
  songs: []
};

rl.question("What is your fav singer? ", function(answer) {
  singer.name = answer;

  //creating a file for this singer
  fs.writeFileSync(singer.name+".md", `${singer.name}\n====================\n\n`); 

  rl.setPrompt(`What's your fav songs for ${singer.name} ?`);
  rl.prompt();

  rl.on('line', function(song) {
    singer.songs.push(song.trim());
    fs.appendFile(singer.name+".md", `* ${song.trim()} \n`);
    //***** WHY IF ITS EXIT ITS NEVER APPEND IT TO THE FILE
    console.log(`* ${song.trim()} \n`);

    if (song.toLowerCase().trim() === 'exit') {
      fs.appendFile(singer.name+".md", "Bye"); 
      //***** WHY ITS NEVER APPEND IT TO THE FILE
      rl.close();       
    } else {
      rl.setPrompt(`what else would ${singer.name} say? ('exit'to leave)`);
      rl.prompt();
    }
  });
});

rl.on ('close', function() {
  console.log ("%s is a real person that says %j", singer.name, singer.songs);
  process.exit();
});

Because fs.appendFile is asynchronous. 因为fs.appendFile是异步的。 When you call it, io operations are queued only. 当您调用它时,io操作仅排队。 Unfortunately, your script exits before the real io-operations happen. 不幸的是,您的脚本在真正的io操作发生之前就退出了。

So. 所以。 you have to use either fs.appendFileSync or fs.appendFile with callback (the 3rd argument) and when the callback is called, do all further activities. 您必须将fs.appendFileSyncfs.appendFile与回调(第3个参数)一起使用,并在调用回调时执行所有进一步的操作。

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

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