Skip to content

Commit

Permalink
feat: compile by content (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
anikghosh256 committed Apr 2, 2024
1 parent 9eb88f0 commit 42ec7b4
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const compiled = compile('filedir/filename.ct', { name: 'John' }); // filepath a
// index.js
const compile = require('@anikghosh256/compile-template');

const compiled = compile('template.ct', { name: 'John' });
const compiled = compile('template.ct', { name: 'John' }); // you can pass file content as third argument
console.log(compiled); // you can also write to a file or do whatever you want with the compiled template
```

Expand Down
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ const functions = require('./helpers/functions')
/**
* Read file and compile it with variables.
*
* @param {string} filePath - Path to file.
* @param {string} filePath - Path to file (if you just want to compile a string, pass null).
* @param {object} variables - Variables to compile.
* @param {string} content - File content to compile (if you don't have a file URL).
* @returns {string} Compiled content.
*/
function compile(filePath, variables = {}) {
function compile(filePath = null, variables = {}, fileContent = null) {
let content = fileContent
// Read the content of the file
const content = fs.readFileSync(filePath, 'utf8')
if (filePath) {
content = fs.readFileSync(filePath, 'utf8')
}

// Regex pattern for variables. It can be ${name} or ${f(name)}
const pattern = /\$\{(\w+|\w+\(\w+\))\}/g
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anikghosh256/compile-template",
"version": "1.3.0",
"version": "1.4.0",
"description": "Minimal templates for Node.js",
"main": "index.js",
"scripts": {
Expand Down
12 changes: 11 additions & 1 deletion test/main.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe('compile', () => {
})
})

describe('compile', () => {
describe('Time test', () => {
const filePath = join(__dirname, 'time-template.ct')

it('should return time', () => {
Expand All @@ -27,3 +27,13 @@ describe('compile', () => {
expect(parseInt(result)).not.toBeNaN()
})
})

describe('Content test', () => {
const content = 'Hello ${name}'

it('should return time', () => {
const result = compile(null, { name: 'Q' }, content).trim()

expect(result).toBe('Hello Q')
})
})

0 comments on commit 42ec7b4

Please sign in to comment.