Node.js Write a line into a .txt file

前端 未结 4 1596
难免孤独
难免孤独 2020-12-04 17:24

I want to create a simple Log System, which prints a line before the past line into a txt file by using Node.js, but i dont know how the File System from Node.js works. Can

相关标签:
4条回答
  • 2020-12-04 17:58

    I did a log file which prints data into text file using "Winston" log. The source code is here below,

    const { createLogger, format, transports } = require('winston');
    var fs = require('fs')
    var logger = fs.createWriteStream('Data Log.txt', {`
    flags: 'a' 
    })
    const os = require('os');
    var sleep = require('system-sleep');
    var endOfLine = require('os').EOL;
    var t = '             ';var s = '         ';var q = '               ';
    var array1=[];
    var array2=[];
    var array3=[];
    var array4=[];
    
    array1[0]  =  78;`
    array1[1]  =  56;
    array1[2]  =  24;
    array1[3]  =  34;
    
    for (var n=0;n<4;n++)
    {
    array2[n]=array1[n].toString();
    }
    
    for (var k=0;k<4;k++)
    {
    array3[k]=Buffer.from('                    ');
    }
    
    for (var a=0;a<4;a++)  
    {
    array4[a]=Buffer.from(array2[a]);
    }
    
    for (m=0;m<4;m++)
    {
    array4[m].copy(array3[m],0);
    }
    
    logger.write('Date'+q);
    logger.write('Time'+(q+'  '))
    logger.write('Data 01'+t);
    logger.write('Data 02'+t); 
    logger.write('Data 03'+t);
    logger.write('Data 04'+t)
    
    logger.write(endOfLine);
    logger.write(endOfLine);
    enter code here`enter code here`
    }
    
    function mydata()      //user defined function
    {
    logger.write(datechar+s);
    logger.write(timechar+s);
    for ( n = 0; n < 4; n++) 
    {
    logger.write(array3[n]);
    }
    logger.write(endOfLine); 
    }
    
    for (;;)
    }
    var now = new Date();
    var dateFormat = require('dateformat');
    var date = dateFormat(now,"isoDate");
    var time = dateFormat(now, "h:MM:ss TT ");
    var datechar = date.toString();
    var timechar = time.toString();
    mydata();
    sleep(5*1000);
    }
    
    0 讨论(0)
  • 2020-12-04 17:59

    Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

    The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

    var fs = require('fs')
    fs.appendFile('log.txt', 'new data', function (err) {
      if (err) {
        // append failed
      } else {
        // done
      }
    })
    

    But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

    var fs = require('fs')
    var logger = fs.createWriteStream('log.txt', {
      flags: 'a' // 'a' means appending (old data will be preserved)
    })
    
    logger.write('some data') // append string to your file
    logger.write('more data') // again
    logger.write('and more') // again
    

    Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

    logger.end() // close string
    
    0 讨论(0)
  • 2020-12-04 18:18

    Step 1

    If you have a small file Read all the file data in to memory

    Step 2

    Convert file data string into Array

    Step 3

    Search the array to find a location where you want to insert the text

    Step 4

    Once you have the location insert your text

    yourArray.splice(index,0,"new added test");
    

    Step 5

    convert your array to string

    yourArray.join("");
    

    Step 6

    write your file like so

    fs.createWriteStream(yourArray);
    

    This is not advised if your file is too big

    0 讨论(0)
  • 2020-12-04 18:23

    Simply use fs module and something like this:

    fs.appendFile('server.log', 'string to append', function (err) {
       if (err) return console.log(err);
       console.log('Appended!');
    });
    
    0 讨论(0)
提交回复
热议问题