Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
convert nonbuffer data to string in fs.writeFile/Sync
Browse files Browse the repository at this point in the history
Fixes #657.
  • Loading branch information
sciolist authored and koichik committed Jul 23, 2011
1 parent 2fe780b commit fa829b0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ fs.writeFile = function(path, data, encoding_, callback) {
if (openErr) {
if (callback) callback(openErr);
} else {
var buffer = Buffer.isBuffer(data) ? data : new Buffer(data, encoding);
var buffer = Buffer.isBuffer(data) ? data : new Buffer('' + data, encoding);
writeAll(fd, buffer, 0, buffer.length, callback);
}
});
Expand All @@ -575,7 +575,7 @@ fs.writeFile = function(path, data, encoding_, callback) {
fs.writeFileSync = function(path, data, encoding) {
var fd = fs.openSync(path, 'w');
if (!Buffer.isBuffer(data)) {
data = new Buffer(data, encoding || 'utf8');
data = new Buffer('' + data, encoding || 'utf8');
}
var written = 0;
var length = data.length;
Expand Down
22 changes: 21 additions & 1 deletion test/simple/test-fs-write-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var filename = join(common.fixturesDir, 'test.txt');

common.error('writing to ' + filename);

var n = 220;
var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' +
'广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' +
'南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' +
Expand Down Expand Up @@ -71,11 +72,30 @@ fs.writeFile(filename2, buf, function(e) {
});
});

// test that writeFile accepts numbers.
var filename3 = join(common.fixturesDir, 'test3.txt');
common.error('writing to ' + filename3);

fs.writeFile(filename3, n, function(e) {
if (e) throw e;

ncallbacks++;
common.error('file3 written');

fs.readFile(filename3, function(e, buffer) {
if (e) throw e;
common.error('file3 read');
ncallbacks++;
assert.equal(Buffer.byteLength('' + n), buffer.length);
});
});


process.addListener('exit', function() {
common.error('done');
assert.equal(4, ncallbacks);
assert.equal(6, ncallbacks);

fs.unlinkSync(filename);
fs.unlinkSync(filename2);
fs.unlinkSync(filename3);
});

0 comments on commit fa829b0

Please sign in to comment.