juliascoding juliascoding - 11 months ago 32
Node.js Question

learning node and modules / creating a file using

Im really new to node and feel like I understand nothing. I was watching a tutorial where the fs.writeFileSync creates a new file. However my code doesn't work and no file is being created-does someone know why? Also why do I need

var fs=require("fs");

? As I understand fs is a build in module and if we require something, there should be another file that exports something (which we require using the fs module)? Node is kind of hard to understand and would appreciate some explanation! Thanks

var fs=require("fs");
fs.writeFileSync("contents.txt","Thats a new file")


fs is indeed a node built-in module, and as other modules, you must require it to use its capabilities. the file you're referring is present internally, so you don't have to npm install it.

And regarding your code, fs.writeFileSync should work as you used it, however, when you tried to print it, you used this function again, this time with no contents, what probably caused the mix-up. Code that should work perfectly is:

//Requiring the fs module in order to use it later on
var fs = require('fs');

//Writing "Thats a new file" as text to a new file called "contents.txt" in the same directory as the script file.
fs.writeFileSync('contents.txt', 'Thats a new file');

//If you want to print the file, read it, like so.

Also, I think you should continue reading about node's async capabilities so you can understand better this technology and what is it good for. This is one site you can learn from but there are a lot of other good ones out there.