0

I have an array of 32 strings called "arr" and I'm trying to save it to a file (like a txt file). I'm doing this in javascript because I'm getting this array from an html page.

I've tried this solution : node.js - how to write an array to file

So this code :

var fs = require('fs');

var file = fs.createWriteStream('array.txt');
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();

results for me this error :

Error: Module name "fs" has not been loaded yet for context: _. Use require([])

I saw a solution there : https://requirejs.org/docs/errors.html#scripterror and tried this one :

require(['foo'], function (foo) {
    //foo is now loaded.
});

but it still results 3 errors :

  • "Failed to load resource: the server responded with a status of 404 (Not Found)"
  • "Refused to execute http://[...]/scripts/fs.js as script because "X-Content-Type-Options: nosniff" was given and its Content-Type is not a script MIME type. defaultOnError — require.js:5:1663"
  • "Error: Script error for "fs""

I'm a beginner in Javascript and I don't really understand how to use require.js. I tried to find a solution but I everything resulted to those errors.

Could you help me to write arrays in a text file ? Thank you for your help !

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
JuniJ
  • 1
  • All you need is something like this `await fs.promises.writeFile("file.txt", arr.join(","));`, but this runs only in a nodejs server, not in a browser. Browser Javascript code can't generally write to your local file system for security reasons. – jfriend00 May 06 '22 at 14:52
  • Welcome JuniJ :) In which environment are you running this script? You are speaking of a website, so are you running it in the browser ? Or is it in a node.js console/script? – Entilore May 06 '22 at 14:53
  • The stackoverflow answer you mentioned above is for 2 dimensional array.If you have a simple array with 32 strings, you don't need to use `v.join`. Just simply `file.write(v + "\n");` – Inder May 06 '22 at 14:55

0 Answers0