Read the file in Node.js

I am very puzzled by reading files in Node.js.

fs.open('./start.html', 'r', function(err, fileToRead){ if (!err){ fs.readFile(fileToRead, {encoding: 'utf-8'}, function(err,data){ if (!err){ console.log('received data: ' + data); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); }else{ console.log(err); } }); }else{ console.log(err); } }); 

The start.html file is in the same directory as the file that is trying to open and read it.

However, in the console, I get:

{[Error: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', path: './start.html'}

Any ideas?

+129
Aug 22 '13 at 16:43
source share
8 answers

Use path.join(__dirname, '/start.html') ;

 var fs = require('fs'), path = require('path'), filePath = path.join(__dirname, 'start.html'); fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (!err) { console.log('received data: ' + data); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); } else { console.log(err); } }); 

Thanks dc5.

+169
Nov 01 '13 at 7:13
source share

With Node 0.12, you can now do this synchronously:

  var fs = require('fs'); var path = require('path'); // Buffer mydata var BUFFER = bufferFile('../public/mydata.png'); function bufferFile(relPath) { return fs.readFileSync(path.join(__dirname, relPath)); // zzzz.... } 

fs is a file system. readFileSync () returns a buffer or string if you ask.

fs correctly assumes that relative paths are a security issue. path is a workaround.

To load as a string, specify the encoding:

 return fs.readFileSync(path,{ encoding: 'utf8' }); 
+31
Apr 26 '15 at 4:10
source share

one). For ASync:

 var fs = require('fs'); fs.readFile(process.cwd()+"\\text.txt", function(err,data) { if(err) console.log(err) else console.log(data.toString()); }); 

2). To sync:

 var fs = require('fs'); var path = process.cwd(); var buffer = fs.readFileSync(path + "\\text.txt"); console.log(buffer.toString()); 
+16
Oct 23 '16 at 7:21
source share

Run this code, it will extract data from the file and display it on the console

 function fileread(filename){ var contents= fs.readFileSync(filename); return contents; } var fs =require("fs"); // file system var data= fileread("abc.txt"); //module.exports.say =say; //data.say(); console.log(data.toString()); 
+3
Sep 23 '16 at 7:26
source share
 var fs = require('fs'); var path = require('path'); exports.testDir = path.dirname(__filename); exports.fixturesDir = path.join(exports.testDir, 'fixtures'); exports.libDir = path.join(exports.testDir, '../lib'); exports.tmpDir = path.join(exports.testDir, 'tmp'); exports.PORT = +process.env.NODE_COMMON_PORT || 12346; // Read File fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) { if (err) { got_error = true; } else { console.log('cat returned some content: ' + content); console.log('this shouldn\'t happen as the file doesn\'t exist...'); //assert.equal(true, false); } }); 
+2
Nov 22 '13 at 11:27
source share

If you want to know how to read a file in a directory and do something with it, then you go. It also shows how to run a command through a power shell . This is in TypeScript ! I had problems with this, so I hope this helps someone once. Feel free to vote against me if you think this is useless. This made for me webpack all my .ts files in each of my directories in a specific folder in order to prepare for deployment. Hope you can use it!

 import * as fs from 'fs'; let path = require('path'); let pathDir = '/path/to/myFolder'; const execSync = require('child_process').execSync; let readInsideSrc = (error: any, files: any, fromPath: any) => { if (error) { console.error('Could not list the directory.', error); process.exit(1); } files.forEach((file: any, index: any) => { if (file.endsWith('.ts')) { //set the path and read the webpack.config.js file as text, replace path let config = fs.readFileSync('myFile.js', 'utf8'); let fileName = file.replace('.ts', ''); let replacedConfig = config.replace(/__placeholder/g, fileName); //write the changes to the file fs.writeFileSync('myFile.js', replacedConfig); //run the commands wanted const output = execSync('npm run scriptName', { encoding: 'utf-8' }); console.log('OUTPUT:\n', output); //rewrite the original file back fs.writeFileSync('myFile.js', config); } }); }; // loop through all files in 'path' let passToTest = (error: any, files: any) => { if (error) { console.error('Could not list the directory.', error); process.exit(1); } files.forEach(function (file: any, index: any) { let fromPath = path.join(pathDir, file); fs.stat(fromPath, function (error2: any, stat: any) { if (error2) { console.error('Error stating file.', error2); return; } if (stat.isDirectory()) { fs.readdir(fromPath, (error3: any, files1: any) => { readInsideSrc(error3, files1, fromPath); }); } else if (stat.isFile()) { //do nothing yet } }); }); }; //run the bootstrap fs.readdir(pathDir, passToTest); 
+2
Nov 16 '18 at 15:07
source share

simple synchronous method with a node:

 let fs = require('fs') let filename = "your-file.something" let content = fs.readFileSync(process.cwd() + "/" + filename).toString() console.log(content) 
0
May 12 '19 at 15:22
source share

Simple use:

  const Store = require('data-store'); const store = new Store({ path: 'filepath/file.json' }); 

for reading:

  store.get('keyname'); 

to update:

  store.set('keyname',value); 
0
Jun 05 '19 at 13:11
source share



All Articles