Server-Side Coding with JavaScript:
State: Files


Server-Side JavaScript: Files

Let's add a 'publish article' form to the blog.

API Design

Article Schema:

field type description
id integer unique among all articles; corresponds to file name e.g. 1.json
author string
title string
body string someday we'll make this Markdown
 "id": 1,
 "title": "How to Cross a Rubicon",
 "author": "Julius Caesar",
 "body": "Lorem ipsum dolor..."


POST /articles create a new article


NodeJS has a nice fs library built in that has some smooth ways of reading and writing files.

Code - find id

  // find the highest id...
  let id = articles.reduce((topId, article) => {
    return Math.max(topId,;
  }, 1);
  // ...and pick a higher one
  let newId = id + 1;

Code - read params, write file

  assistant.parsePostParams((params) => {
    let article = {
      id: newId,
      title: params.title,
      body: params.body
    let articleDataFile = $path.join(articlesDir, newId + ".json");
    fs.writeFile(articleDataFile, JSON.stringify(article), (err) => {
      if (err) {
        assistant.sendError(500, err);
      } else {

Code - redirect

  sendRedirect(path) {
    let message = `Redirecting to ${path}`;
    this.response.statusCode = 302;
    this.response.setHeader('Location', path);
    this.finishResponse('text/plain', message);


comments powered by Disqus