Ask coding questions

← Back to all posts
JavaScript write to file
SirRedan (1)

i've been trying to get to run code that writes to a textfile, i got it to work once. but then i had to refresh and now it no longer wants to accept the same code. i have to write to file as the console doesnt want to display the entire output if the input gets too big

i've now found a workaround for my issue, but i'd still like to look for other solutions to JS / node.js write to file

my issue was: After first run the package pulled with var writeFile = require('write'); "write" wouldnt work properly ie. not writing to file citing "undefined"

delete package-lock
delete textfile made
rerun code
"fresh package" downloaded
textfile with expected output present

any easier way to write to file in

code for reference

Answered by mat1 (4423) [earned 5 cycles]
View Answer
mat1 (4423)

You can write to a file in NodeJS with the builtin filesystem (fs) api. You can access it by requiring it with this line

const fs = require('fs')

and you can use it by doing either this to write it synchronously

fs.writeFileSync("test.txt", "Hello world")

or this to use a callback

fs.writeFile("test.txt", "Hello world", function() {
  // run this after file gets edited

Please upvote my comment if it was helpful or useful. Thanks!

ElliotMassey (0)

@mat1 is there a way to do this without deleating previous text?