read file node
snippet in javascript

read file node

user1361

// load fs
const fs = require("fs");
// read the file
const content = fs.readFileSync("./my_file.txt");
// print it
console.log(content.toString());

node read file

user7973

var http = require('http');
var fs = require('fs');
http.createServer(function 
  (req, res) {
  fs.readFile('demofile1.html', function(err, data) {

      
  res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    
  res.end();
  });
}).listen(8080); 

nodejs readfile

user1150

const fs = require('fs');

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

read file in nodejs using fs

user7152

let myFile = "./myText.txt";
const fs = require("fs");
		
app.all('/test', async (req, res) => {
	try {
		const readData = fs.readFileSync(myFile, 'utf8');
		if (readData) {
			res.send(readData)
		}
	} catch (error) {
		res.send("something is wrong", error)
	}
})

readfile nodejs

user3543

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

nodejs open file

user3239

fs = require('fs')
fs.readFile('/etc/hosts', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data);
});