简体   繁体   中英

Reading a determined size of a string from end of file in Node.js

I appended a string to a file by fs.appendFileSync() and then I want to get it from that file. I try to use fs.readSync . But it returns Error: Unknown encoding: 6 . How can I get the appended string from a file in Node.js? I know the size of string. My code for appending:

fs.appendFileSync('A.dmg','behdad');

and for reading the appended string:

var fd = fs.openSync('A.dmg','w+');
var buffer = '';
var res = fs.readSync(fd,buffer,0,6,fs.statSync('A.dmg').size);
console.log(buffer);
console.log(res);

Edited:

var fs = require('fs');
var fd = fs.openSync('A.dmg','r+');
var size = fs.statSync('A.dmg').size;
var buffer = Buffer.alloc(size);
var res = fs.readSync(fd, buffer, 0, size, 0);
console.log(buffer.toString());
console.log(res);

First, understand the difference between r+ and w+ modes:

r+ : Open a text file for update (that is, for both reading and writing).
w+ : Open a text file for update (reading and writing), first truncating the file to zero length if it exists or creating the file if it does not exist.

Since you want to open the file for reading and maybe updating it later, you should open the file in r+ mode.

Second, the last argument passed to fs.readSync() in your code doesn't make sense to me. The last argument is the position . If you really want to read the 6 characters, then why specify the position of the file pointer to 6? You want to read the file from the start, right?

Now, coming back to the main point: The second argument passed to readSync() in your code is of datatype: String , which is immutable. So, now the call to fs.readSync() falls back to the old syntax...

fs.readSync(fd, length, position, encoding) : Synchronous version of fs.read . Returns an array [data, bytesRead] .

...and it thinks that 6 is the encoding which you wish to specify, which is clearly not the case.

Hence, if you are using a new version of node, your code should be something like:

var fs = require('fs');
fs.appendFileSync('A.dmg','behdad');
var fd = fs.openSync('A.dmg','r+');
var size = fs.statSync('A.dmg').size;
var buffer = Buffer.alloc(size);
var res = fs.readSync(fd, buffer, 0, size, 0);
console.log(buffer.toString());
console.log(res);

If you are using an old version of node:

var fs = require('fs');
fs.appendFileSync('A.dmg','behdad');
var fd = fs.openSync('A.dmg','r+');
var size = fs.statSync('A.dmg').size;
var res = fs.readSync(fd, size, 0, 'utf8');
console.log(res);

Read the discussion at https://github.com/nodejs/node/issues/2820

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