2

I'm just getting started with node.js. This is my first attempt ever and I'm having trouble reading from a txt file to the node.js terminal in windows 7. Using the Node.js application in windows, I typed "node sample.js" and the sample.js and sample.txt files are in a folder on my desktop but the node.exe application doesnt read the file. Also I'm not sure how it would know the directory path Any insight? Here's my code:

var fs = require("fs");
console.log("Starting");
fs.readFile("sample.txt", function(error, data) {
    console.log("Contents of file: " + data);
});
console.log("Carrying on executing");
1
  • 2
    Did you check the error? Add a line if(error) throw error; before you print out the data Commented Sep 14, 2013 at 19:54

2 Answers 2

1

You should take a look at the error parameter (log it or throw it) to see what's going wrong. Because you're using a relative path, it will be looking relative to the current working directory.

node.js docs:

Relative path to filename can be used, remember however that this path will be relative to process.cwd().

You should also be aware that the last line of your code will actually execute first (probably) because readFile is asynchronous. (This is a key node.js concept.)

Sign up to request clarification or add additional context in comments.

Comments

1

Try using

fs.readFile(__dirname + "/sample.txt", function(error, data) {

__dirname is actually the current directory of the file which you are in.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.