0

I've got a node.js app where I'm trying to read and write numbers and stings to files.

I'm currently writing

fs.writeFileSync(myPath, value);

where value can be either a number or a string.

When I read the file

fs.readFileSync(myPath,'utf-8');

I get the file as a string. I'm hoping there is a way for me to read the file, without needing to specify if the contents of the file are a number or a string. Is this possible?

The way around it, I suspect, is to try to convert the string to a number and see if it fails, but I'm hoping there is a better way. I'm happy to use fs.writeStream/fs.readStream with buffers (actually preferrable), but I'm not sure exactly what the best path here is.

1 Answer 1

1

When the encoding option is specified then readFileSync returns a string.
Otherwise it returns a buffer.

So say the docs

To read a buffer you'd normally use .toString('utf8') in Node, so that gets you nowhere.
In other words, reading a file will return a string in Node, and not a valid integer, but you can check if the string is a number, it's as easy as calling isNaN

var is_number = !isNaN(file_string);
Sign up to request clarification or add additional context in comments.

2 Comments

I was hoping there would be something nicer, but I could do return isNaN(file_output) ? file_output : parseInt(file_output)
Yes you could, remember the radix in parseInt!

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.