Commit b9878201 authored by Frauke's avatar Frauke
Browse files

Updated fileUtils.

Added tests for fileUtils.
parent a0941a1f
This diff is collapsed.
......@@ -4,7 +4,8 @@
"description": "Use libsodium to implement Spike 1: OpenCrypto",
"main": "./server/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test": "mocha server/**/*.test.js",
"test-watch": "nodemon --exec npm test",
"watch": "nodemon",
"start": "gulp js:bundle | node ./server/index.js"
},
......@@ -16,9 +17,12 @@
"license": "ISC",
"devDependencies": {
"browserify": "^15.1.0",
"expect": "^22.1.0",
"gulp": "^3.9.1",
"gulp-rename": "^1.2.2",
"mocha": "^5.0.0",
"standard": "^10.0.3",
"supertest": "^3.0.0",
"vinyl-source-stream": "^2.0.0"
},
"dependencies": {
......
const fs = require('fs')
const path = require('path')
// Writes a string to the filesystem.
function writeFile (fileName, value) {
function writeFile (fileName, value, pathName) {
return new Promise((resolve, reject) => {
let wstream = fs.createWriteStream(fileName)
wstream.write(value)
wstream.end()
makeDir(pathName).then(() => {
fs.writeFile(path.join(pathName, fileName), value, (err) => {
if (err) {
reject(err)
}
resolve()
})
}).catch((err) => reject(err))
})
}
wstream.on('finish', () => { resolve() })
wstream.on('error', (err) => { reject(err) })
// Creates a dir on the filesystem if it does not exist.
function makeDir (pathName) {
return new Promise((resolve, reject) => {
if (!fs.existsSync(pathName)) {
fs.mkdir(pathName, (err) => {
if (err) {
reject(err)
}
resolve()
})
} else {
resolve()
}
})
}
// Reads a file from the filesystem.
function readFile (fileName) {
return new Promise((resolve, reject) => {
let readStream = fs.createReadStream(fileName)
readStream.on('error', (err) => { reject(err) })
readStream.on('data', (chunk) => {
resolve(chunk)
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
}
......
const expect = require('expect')
const fileUtils = require('../fileUtils')
const fs = require('fs')
const testString = 'This is a unit test string'
describe('File utils tests', () => {
after(() => {
fs.unlink('./server/test/test.txt', (err) => {
if (err) {
console.log(err)
return
}
fs.rmdir('./server/test', (err) => {
if (err) {
console.log(err)
}
})
})
})
it('should write a file to the filesystem', (done) => {
fileUtils.writeFile('test.txt', testString, './server/test').then(() => {
fs.access('./server/test/test.txt', (err) => {
if (err) {
return done(err)
}
done()
})
}).catch((err) => done(err))
})
it('should read a file from the filesystem', (done) => {
fileUtils.readFile('./server/test/test.txt').then((file) => {
expect(file).toBe(testString)
done()
}).catch((err) => done(err))
})
})
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment