From fa829b0fd31b4723a6d5ffb77816b06baa838267 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Pihlstr=C3=B6m?= Date: Fri, 11 Feb 2011 03:35:39 +0100 Subject: [PATCH] convert nonbuffer data to string in fs.writeFile/Sync Fixes #657. --- lib/fs.js | 4 ++-- test/simple/test-fs-write-file.js | 22 +++++++++++++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index b907021b5cc6..7cad38ad1f13 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -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); } }); @@ -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; diff --git a/test/simple/test-fs-write-file.js b/test/simple/test-fs-write-file.js index 780ac6c149eb..b5842c4e3dfa 100644 --- a/test/simple/test-fs-write-file.js +++ b/test/simple/test-fs-write-file.js @@ -28,6 +28,7 @@ var filename = join(common.fixturesDir, 'test.txt'); common.error('writing to ' + filename); +var n = 220; var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + @@ -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); });