The decodeJupyterNotebook
function decodes the content of a Jupyter Notebook file by reading it into a string, parsing it as JSON, and logging the content of code cells. It takes a single argument, filePath
, which is the path to the Jupyter Notebook file, and raises an error if there are any issues with file reading or parsing.
const fs = require('fs');
function decodeJupyterNotebook(filePath) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
try {
const notebook = JSON.parse(data);
const cells = notebook.cells;
cells.forEach(cell => {
if (cell.cell_type === 'code') {
const source = cell.source.join('');
console.log('Decoded code cell content:');
console.log(source);
}
});
} catch (err) {
console.error('Error parsing notebook:', err);
}
});
}
// Usage example
decodeJupyterNotebook('Untitled.ipynb');
// Import the built-in readline module for file operations
const fs = require('fs');
const path = require('path');
/**
* Decodes a Jupyter Notebook file and logs the content of code cells.
*
* @param {string} filePath - The path to the Jupyter Notebook file.
*/
function decodeJupyterNotebook(filePath) {
// Check if the file path is a string
if (typeof filePath!=='string') {
throw new TypeError('File path must be a string');
}
// Check if the file exists
if (!fs.existsSync(filePath)) {
console.error(`File not found: ${filePath}`);
return;
}
// Read the file contents synchronously to avoid callback hell
const fileContents = fs.readFileSync(filePath, 'utf8');
try {
// Parse the Jupyter Notebook file contents as JSON
const notebook = JSON.parse(fileContents);
const cells = notebook.cells;
// Filter and log the content of code cells
cells.forEach((cell) => {
if (cell.cell_type === 'code') {
// Join the code cell's source code into a single string
const source = cell.source.join('\n');
console.log(`Decoded code cell content from ${path.basename(filePath)} at line ${cell.metadata.linetracker.first_execution_info.execution_count}:`);
console.log(source);
}
});
} catch (error) {
console.error(`Error parsing notebook: ${error.message}`);
}
}
// Usage example
decodeJupyterNotebook('Untitled.ipynb');
Decodes the content of a Jupyter Notebook file.
filePath
: Path to the Jupyter Notebook file to decode.filePath
into a string using fs.readFile
.JSON.parse
.Call the decodeJupyterNotebook
function with the path to a Jupyter Notebook file as an argument.
decodeJupyterNotebook('Untitled.ipynb');