2

Hello I have a question with node.js mainly with creating new larger files.

I understand how to do stuff such as

fs.writeFile('ss.js', 'console.log("hello")');

But my problem comes when I need to create a file that has 5 or more lines, AKA all the files. I'm not sure where to even start on this problem. I've been through a lot of tutorials and all of them jusy say, "Now create a file and fill it with these lines of code.", but none of them actually go indepth into how to create a file with multiple lines of code.

Greatly appreciated if anyone can go over this basic step. Thanks!

1
  • you can add newline character "\r\n" in your text to create multiline content. Look at appendFile method as well. nodejs.org/api/fs.html Commented May 27, 2015 at 1:17

1 Answer 1

2

You're kind of undermining "large files". Those are simply line-breaks, which is (at least on Unix) around 5 extra bytes (since linebreaks are represented as a single byte).

Take this example:

fs.writeFile("test.js", "var test = 'ey b0ss';\nconsole.log(test);\nif (true) {\nconsole.log('yey');\n}");

In this example, line-breaks are represented as \n, considering you're on a Unix machine, this would work fine (If you're on a Windows machine, I think \r is the alternative)... (You can use the \r\n combo to represent a line-break on both OS's.)

The output of this on a Unix machine is:

var test = 'ey b0ss';
console.log(test);
if (true) {
console.log('yey');
}

When actually creating large files (in terms of storage), in my opinion, it'd be best to represent it as a buffer.

For instance, say we wanted to create a file that had 100,000 "a" characters in it.

var largeBuffer = new Buffer(""), i,
anotherBuffer = new Buffer("a"),
fs = require("fs");

for (i=0; i<=100000; i++) {
  largeBuffer = Buffer.concat([largeBuffer, anotherBuffer]);
}

fs.writeFile("a.txt", largeBuffer);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.