0

My current code is something like this.

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

But it creates a new file outside the folder. How do i make it edit the log.txt file inside my folder?

  • 1
    Possible duplicate: [How to append to a file in Node?](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node). There is an answer to [reuse the file handle](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node/43370201#43370201) – Audwin Oyong Aug 09 '21 at 12:56
  • `'log.txt'` create the file in the current working directory. `inside my folder?` is that folder always the folder in where the file is located in which this code is? – t.niese Aug 09 '21 at 12:57

2 Answers2

1

You can use __dirname

var fs = require('fs')
fs.appendFile(__dirname + '/log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})
user3601578
  • 1,310
  • 1
  • 18
  • 29
  • 1
    Just as a note: don't use `__dirname + '/log.txt'` use `path.join(__dirname, 'log.txt')` instead to combine two or more path pices. – t.niese Aug 09 '21 at 12:58
0

What you could do is use path.resolve() to get the absolute path.

var fs = require('fs');
const path = require('path');

fs.appendFile(path.resolve('log.txt'), 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})
KZander
  • 300
  • 4
  • 16
  • `path.resolve('log.txt')` and `'log.txt'` should in this case result int he equivalent path that is used. – t.niese Aug 09 '21 at 14:42