I’m started learning nodejs and faced the following problem. It is necessary to create a file in which there is conditionally nothing, and when it is created, a greeting is displayed, with a suggestion for the subsequent input of text (any) which, in turn, will be saved in the created file. Text input continues until the thread is stopped via ctrl+c, and when pressed, displays the farewell text (sry my eng ^_^)
Gave a couple of examples
const fs = require('fs');
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
fs.appendFile('server.txt', greeting, function (err) {
if (err) return console.log(err);
console.log('Appended!');
});
const greeting = rl.question('Hi user, what your name? ', (answer) => {
console.log(`Hi ${answer}, nice to meet you! Сontinue...`);
rl.on('line', (input) => {
console.log(`Your thoughts: ${input}`);
});
});
let data = rl.on('line', (input) => {
console.log(`Received: ${input}`);
});
let hi = 'Hi user, what your name? ';
newFunction();
function newFunction () {
fs.writeFile(
'greteng.txt',
hi,
{
encoding: 'utf8',
flag: 'w',
mode: 0o666,
},
(err) => {
if (err) console.log(err);
else {
console.log('File written successfullyn');
console.log('The written has the following contents:');
console.log(fs.readFileSync('greteng.txt', 'utf8'));
}
},
);
}
newFunction(data);