Load content from files (and sometimes parse) in Sapper Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)

Can anything be seen from the center of the Boötes void? How dark would it be?

Apollo command module space walk?

Why are there no cargo aircraft with "flying wing" design?

Would "destroying" Wurmcoil Engine prevent its tokens from being created?

Delete nth line from bottom

Extracting terms with certain heads in a function

Is it fair for a professor to grade us on the possession of past papers?

Can a party unilaterally change candidates in preparation for a General election?

An adverb for when you're not exaggerating

Generate an RGB colour grid

Why wasn't DOSKEY integrated with command.com?

What is the longest distance a player character can jump in one leap?

Where are Serre’s lectures at Collège de France to be found?

What causes the direction of lightning flashes?

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

How to find 'n' nodes where all distances between them are greater than 'k'?

Do wooden building fires get hotter than 600°C?

Most bit efficient text communication method?

Why are the trig functions versine, haversine, exsecant, etc, rarely used in modern mathematics?

T-test, ANOVA or Regression, what's the difference?

Is it a good idea to use CNN to classify 1D signal?

On SQL Server, is it possible to restrict certain users from using certain functions, operators or statements?

What is this building called? (It was built in 2002)

Why do we bend a book to keep it straight?



Load content from files (and sometimes parse) in Sapper



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0












$begingroup$


I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.



Here is an excrept from my directory structure:



content
|- index.md
|- services.txt
|- about
|- index.md
|- technologies.html
routes
|- index.html
|- services.html
|- section-[section].json.js
|- about
|- index.html
|- technologies.html


I've made JSON interface section-[section].json.js that is used to request content. The content of sectionX can be in file content/sectionX.ext with whatever extension and the content is also parsed through marked if it's a .md file.



This is how I am loading the content in my routes/services.html:



<script>
export default
preload()
return this.fetch('section-services.json').then(r => r.json()).then(section =>
return section;
);


</script>


Nested files are requested using dot notation, i.e. about.technologies could be resolved either to file content/about/technologies.ext or content/about/technologies/index.ext (similar to how sapper resolves URIs to files).



The part that I would like to have reviewed is my routes/section-[section].json.js. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.



import fs from 'fs'
import path from 'path'
import marked from 'marked'

function getFileFromDir(file, directory)

const filesInDir = fs.readdirSync('content/'+directory, withFileTypes: true)
.filter(f => f.isFile() && file == path.parse(f.name).name)

if (filesInDir.length)

let fileName = 'content/'

if (directory.length)
fileName += directory + '/'

fileName += filesInDir[0].name

return fileName


return null


function getFile(path)

path = path.split('.')

// First try to get the named file
let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
if (file)
return file

// Assume that path is a directory and look for index
file = getFileFromDir('index', path.join('/'))
if (file)
return file

return null


export function get(req, res)
let file = getFile(req.params.section)

if (!file)
return 'Failed to fetch content of section ' + req.params.section

let content = fs.readFileSync(file, 'utf8')

if ('.md' == path.extname(file))
content = marked(content)

res.writeHead(200,
'Content-Type': 'application/json',
'Cache-Control': `max-age=$30 * 60 * 1e3`
)

content = JSON.stringify(content)

res.end(content)



My experience with Node is also fairly limited, any tips appreciated!









share







New contributor




Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$


















    0












    $begingroup$


    I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.



    Here is an excrept from my directory structure:



    content
    |- index.md
    |- services.txt
    |- about
    |- index.md
    |- technologies.html
    routes
    |- index.html
    |- services.html
    |- section-[section].json.js
    |- about
    |- index.html
    |- technologies.html


    I've made JSON interface section-[section].json.js that is used to request content. The content of sectionX can be in file content/sectionX.ext with whatever extension and the content is also parsed through marked if it's a .md file.



    This is how I am loading the content in my routes/services.html:



    <script>
    export default
    preload()
    return this.fetch('section-services.json').then(r => r.json()).then(section =>
    return section;
    );


    </script>


    Nested files are requested using dot notation, i.e. about.technologies could be resolved either to file content/about/technologies.ext or content/about/technologies/index.ext (similar to how sapper resolves URIs to files).



    The part that I would like to have reviewed is my routes/section-[section].json.js. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.



    import fs from 'fs'
    import path from 'path'
    import marked from 'marked'

    function getFileFromDir(file, directory)

    const filesInDir = fs.readdirSync('content/'+directory, withFileTypes: true)
    .filter(f => f.isFile() && file == path.parse(f.name).name)

    if (filesInDir.length)

    let fileName = 'content/'

    if (directory.length)
    fileName += directory + '/'

    fileName += filesInDir[0].name

    return fileName


    return null


    function getFile(path)

    path = path.split('.')

    // First try to get the named file
    let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
    if (file)
    return file

    // Assume that path is a directory and look for index
    file = getFileFromDir('index', path.join('/'))
    if (file)
    return file

    return null


    export function get(req, res)
    let file = getFile(req.params.section)

    if (!file)
    return 'Failed to fetch content of section ' + req.params.section

    let content = fs.readFileSync(file, 'utf8')

    if ('.md' == path.extname(file))
    content = marked(content)

    res.writeHead(200,
    'Content-Type': 'application/json',
    'Cache-Control': `max-age=$30 * 60 * 1e3`
    )

    content = JSON.stringify(content)

    res.end(content)



    My experience with Node is also fairly limited, any tips appreciated!









    share







    New contributor




    Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      0












      0








      0





      $begingroup$


      I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.



      Here is an excrept from my directory structure:



      content
      |- index.md
      |- services.txt
      |- about
      |- index.md
      |- technologies.html
      routes
      |- index.html
      |- services.html
      |- section-[section].json.js
      |- about
      |- index.html
      |- technologies.html


      I've made JSON interface section-[section].json.js that is used to request content. The content of sectionX can be in file content/sectionX.ext with whatever extension and the content is also parsed through marked if it's a .md file.



      This is how I am loading the content in my routes/services.html:



      <script>
      export default
      preload()
      return this.fetch('section-services.json').then(r => r.json()).then(section =>
      return section;
      );


      </script>


      Nested files are requested using dot notation, i.e. about.technologies could be resolved either to file content/about/technologies.ext or content/about/technologies/index.ext (similar to how sapper resolves URIs to files).



      The part that I would like to have reviewed is my routes/section-[section].json.js. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.



      import fs from 'fs'
      import path from 'path'
      import marked from 'marked'

      function getFileFromDir(file, directory)

      const filesInDir = fs.readdirSync('content/'+directory, withFileTypes: true)
      .filter(f => f.isFile() && file == path.parse(f.name).name)

      if (filesInDir.length)

      let fileName = 'content/'

      if (directory.length)
      fileName += directory + '/'

      fileName += filesInDir[0].name

      return fileName


      return null


      function getFile(path)

      path = path.split('.')

      // First try to get the named file
      let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
      if (file)
      return file

      // Assume that path is a directory and look for index
      file = getFileFromDir('index', path.join('/'))
      if (file)
      return file

      return null


      export function get(req, res)
      let file = getFile(req.params.section)

      if (!file)
      return 'Failed to fetch content of section ' + req.params.section

      let content = fs.readFileSync(file, 'utf8')

      if ('.md' == path.extname(file))
      content = marked(content)

      res.writeHead(200,
      'Content-Type': 'application/json',
      'Cache-Control': `max-age=$30 * 60 * 1e3`
      )

      content = JSON.stringify(content)

      res.end(content)



      My experience with Node is also fairly limited, any tips appreciated!









      share







      New contributor




      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.



      Here is an excrept from my directory structure:



      content
      |- index.md
      |- services.txt
      |- about
      |- index.md
      |- technologies.html
      routes
      |- index.html
      |- services.html
      |- section-[section].json.js
      |- about
      |- index.html
      |- technologies.html


      I've made JSON interface section-[section].json.js that is used to request content. The content of sectionX can be in file content/sectionX.ext with whatever extension and the content is also parsed through marked if it's a .md file.



      This is how I am loading the content in my routes/services.html:



      <script>
      export default
      preload()
      return this.fetch('section-services.json').then(r => r.json()).then(section =>
      return section;
      );


      </script>


      Nested files are requested using dot notation, i.e. about.technologies could be resolved either to file content/about/technologies.ext or content/about/technologies/index.ext (similar to how sapper resolves URIs to files).



      The part that I would like to have reviewed is my routes/section-[section].json.js. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.



      import fs from 'fs'
      import path from 'path'
      import marked from 'marked'

      function getFileFromDir(file, directory)

      const filesInDir = fs.readdirSync('content/'+directory, withFileTypes: true)
      .filter(f => f.isFile() && file == path.parse(f.name).name)

      if (filesInDir.length)

      let fileName = 'content/'

      if (directory.length)
      fileName += directory + '/'

      fileName += filesInDir[0].name

      return fileName


      return null


      function getFile(path)

      path = path.split('.')

      // First try to get the named file
      let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
      if (file)
      return file

      // Assume that path is a directory and look for index
      file = getFileFromDir('index', path.join('/'))
      if (file)
      return file

      return null


      export function get(req, res)
      let file = getFile(req.params.section)

      if (!file)
      return 'Failed to fetch content of section ' + req.params.section

      let content = fs.readFileSync(file, 'utf8')

      if ('.md' == path.extname(file))
      content = marked(content)

      res.writeHead(200,
      'Content-Type': 'application/json',
      'Cache-Control': `max-age=$30 * 60 * 1e3`
      )

      content = JSON.stringify(content)

      res.end(content)



      My experience with Node is also fairly limited, any tips appreciated!







      javascript node.js





      share







      New contributor




      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 3 mins ago









      DžurisDžuris

      1012




      1012




      New contributor




      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Džuris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          Džuris is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217640%2fload-content-from-files-and-sometimes-parse-in-sapper%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Džuris is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          Džuris is a new contributor. Be nice, and check out our Code of Conduct.












          Džuris is a new contributor. Be nice, and check out our Code of Conduct.











          Džuris is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217640%2fload-content-from-files-and-sometimes-parse-in-sapper%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订