-2

I want to edit and read a file using JavaScript using the FileReader API. However, all the tutorials I have found ask me to specify the file parameter using the value from <input type="file">. Would I be able to set the file parameter as a file address like 'C:/Users/Code/example.txt'.

FileReader API:

 function printFile(file) {
  const reader = new FileReader();
  reader.onload = function(evt) {
    console.log(evt.target.result);
  };
  reader.readAsText(file);
}
  • No, you would not, because if that was possible, then any website could try and automatically read the contents of any system or other files from known locations. – CBroe Dec 06 '21 at 08:40

1 Answers1

-1

Due to security concerns, you cannot do this in the user's browser, unless the user is uploading. Here is a question that helps you read the file when the user selects it to upload: get the data of uploaded file in javascript

It is however, possible on the server side using nodejs. Here is a sample code that does that on the server side:

const fs = require('fs')

fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})