Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs load file

I want to load test.txt with nodejs.

var fs = require('fs'); fs.readFile('./test.txt', function (err, data) {   if (err) {     throw err;    }   console.log(data); }); 

The path of the server is C:\server\test\server.js. The test.txt is located in the same directory, but I get this error: Error: ENOENT, no such file or directory 'C:\Users\User\test.txt'

like image 247
Danny Fox Avatar asked Mar 27 '12 13:03

Danny Fox


People also ask

How do I read a text file in NodeJs?

We can use the 'fs' module to deal with the reading of file. The fs. readFile() and fs. readFileSync() methods are used for the reading files.

How do you run a file in node?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.

How do I load an asset in NodeJs?

static(path. join(__dirname,'public'))); Then create a folder named public in the project root directory and move the css and js files to this folder. A better way of organising things would be to create folders named css and javascript inside the public directory and then place css and js files in these folders.


2 Answers

Paths in Node are resolved relatively to the current working directory. Prefix your path with __dirname to resolve the path to the location of your Node script.

var fs = require('fs'); fs.readFile( __dirname + '/test.txt', function (err, data) {   if (err) {     throw err;    }   console.log(data.toString()); }); 
like image 159
Rob W Avatar answered Oct 10 '22 22:10

Rob W


With Node 0.12, it's possible to do this synchronously now:

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

fs is the file system. readFileSync() returns a Buffer, or string if you ask.

fs correctly assumes relative paths are a security issue. path is a work-around.

To load as a string, specify the encoding:

return fs.readFileSync(path,{ encoding: 'utf8' }); 
like image 44
Michael Cole Avatar answered Oct 10 '22 21:10

Michael Cole