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'
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.
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.
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.
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()); });
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' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With