Node.js Write a line into a .txt file

时间:2015-10-29 15:44:56

标签: node.js fs

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 someone explain it ?

4 个答案:

答案 0 :(得分:76)

将数据插入文本文件的中间并不是一项简单的任务。如果可能,您应该将其附加到文件的末尾。

将数据附加到某些文本文件的最简单方法是使用fs.appendFile(filename, data[, options], callback) function中的内置fs module

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

但是如果您想多次将数据写入日志文件,那么最好使用fs.createWriteStream(path[, options]) function代替:

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

每次您拨打.write时,节点都会继续将新数据附加到您的文件中,直到您的应用程序关闭,或者您手动关闭调用.end的流:

logger.end() // close string

答案 1 :(得分:2)

只需使用fs模块,如下所示:

fs.appendFile('server.log', 'string to append', function (err) {
   if (err) return console.log(err);
   console.log('Appended!');
});

答案 2 :(得分:2)

第1步

如果你有一个小文件 将所有文件数据读入内存

第2步

将文件数据字符串转换为数组

第3步

搜索数组以查找要插入文本的位置

第4步

一旦你有位置插入你的文字

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

第5步

将数组转换为字符串

yourArray.join("");

第6步

像这样编写你的文件

fs.createWriteStream(yourArray);

如果您的文件太大,则不建议这样做

答案 3 :(得分:0)

我做了一个日志文件,该文件使用“ Winston”日志将数据打印到文本文件中。源代码在下面,

/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'i2cdev001' at '14/11/18 3:11 PM' with Gradle 2.14.1
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.14.1/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'
apply plugin: 'war'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.21'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
}