Skip to content
← Back to Community
JavaScript write to file
Profile icon

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 [earned 5 cycles]
View Answer
Profile icon
Profile icon
Profile icon

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!

Profile icon

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

Profile icon

Microsoft setup home & student 2019 is the software % for college kids and households. Installing setup home pupil 2019, you furthermore mght have the option to down load Home scholar 2019 apps separately. This is the satisfactory element; you get to analyze new things writing on different subjects. They can vary everywhere from clinical resources to the political situation in Uganda. You’ll continually have something to mention in a communication.