1

I want to create a text file in javascript. I have tried this, but it doesn't work:

 var file_name=dir+'/aaa.txt';
 var fso = CreateObject('Scripting.FileSystemObject');
 var s = fsoo.CreateTextFile(file_name, True);
 s.Close();

I need to create an empty file to a path.

UPDATE1: I have also tried this, but doesn't work. Also I can not import System.IO:

 var file_name='aaa.txt';
 StreamWriter sw = new StreamWriter(file_name);
 sw.WriteLine("This is the line");
 sw.Close();

UPDATE2: I also have tryed to execute a unix comand that does 'touch file_name'. However this doesn't work either:

 var sys = require('sys')
 var exec = require('child_process').exec;
 var child;

 child = exec(\"touch\" + file_name, function (error, stdout, stderr) {
    sys.print('stdout: ' + stdout);
    sys.print('stderr: ' + stderr);
    if (error !== null) {
       console.log('exec error: ' + error);
    }
 });

Does anyone know how I should create a file in javascript?

4
  • What exactly are you trying to do? Commented Feb 26, 2014 at 9:46
  • possible duplicate of How to Create a Text File Locally at client side using JavaScript/JQuery Commented Feb 26, 2014 at 9:46
  • Do you want to do this with a browser, and to write to the local filing system? The browser security model will stop you doing that, if so. Commented Feb 26, 2014 at 11:46
  • Are you attempting to run this in a browser? Or in server-side Javascript, in Node for example? Commented Feb 26, 2014 at 16:23

2 Answers 2

0

This project on github looks promising:

https://github.com/eligrey/FileSaver.js

FileSaver.js implements the W3C saveAs() FileSaver interface in browsers that do not natively support it.

Also have a look at the demo here:

http://eligrey.com/demos/FileSaver.js/

Sign up to request clarification or add additional context in comments.

1 Comment

As I see this helps if you want to download(save locally) some file. I only need to create a file on a specific path (similar to touch file in batch).
0

Node.js has a library called FS FS Tutorial

You can easily create files using a built in function as so,

// include node fs module
var fs = require('fs');
 
// writeFile function with filename, content and callback function
fs.writeFile('newfile.txt', 'Learn Node FS module', function (err) {
  if (err) throw err;
  console.log('File is created successfully.');
});

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.