Node.js在.txt文件中写一行 [英] Node.js Write a line into a .txt file

查看:713
本文介绍了Node.js在.txt文件中写一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个简单的日志系统,该日志系统使用Node.js将前一行之前的一行打印到txt文件中,但是我不知道Node.js中的文件系统如何工作.有人可以解释吗?

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 ?

推荐答案

将数据插入文本文件的中间并不是一件容易的事.如果可能的话,应该将其附加到文件末尾.

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.

将数据附加到某些文本文件的最简单方法是使用内置 fs.appendFile(filename, data[, options], callback)函数来自 fs模块:

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
  }
})

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

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

每次您调用.write之前,Node都会一直将新数据追加到您的文件中,直到您的应用程序被关闭,或者直到您手动关闭调用.end的流为止,

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

这篇关于Node.js在.txt文件中写一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆