简体   繁体   中英

writing numbers and strings to a file in node.js

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM